coverage-report

Code coverage report for All files

npmtest-azure-storage (v0.0.1)

Code coverage report for All files

Statements: 16.05% (1368 / 8522)      Branches: 4.11% (136 / 3306)      Functions: 2.28% (32 / 1405)      Lines: 16.64% (1368 / 8220)      Ignored: 26 statements, 1 function, 30 branches     

File Statements Branches Functions Lines
node-npmtest-azure-storage/ 100% (153 / 153) 100% (126 / 126) 100% (28 / 28) 100% (153 / 153)
node-npmtest-azure-storage/node_modules/azure-storage/ 10% (1 / 10) 100% (0 / 0) 0% (0 / 1) 10% (1 / 10)
node-npmtest-azure-storage/node_modules/azure-storage/browser/ 3.36% (5 / 149) 22.22% (4 / 18) 0% (0 / 17) 3.36% (5 / 149)
node-npmtest-azure-storage/node_modules/azure-storage/lib/ 72.41% (42 / 58) 0% (0 / 2) 0% (0 / 11) 72.41% (42 / 58)
node-npmtest-azure-storage/node_modules/azure-storage/lib/common/ 97.06% (33 / 34) 25% (2 / 8) 100% (0 / 0) 97.06% (33 / 34)
node-npmtest-azure-storage/node_modules/azure-storage/lib/common/diagnostics/ 42.42% (14 / 33) 0% (0 / 4) 0% (0 / 11) 42.42% (14 / 33)
node-npmtest-azure-storage/node_modules/azure-storage/lib/common/errors/ 47.06% (16 / 34) 0% (0 / 8) 0% (0 / 5) 47.06% (16 / 34)
node-npmtest-azure-storage/node_modules/azure-storage/lib/common/filters/ 24.77% (27 / 109) 0% (0 / 105) 0% (0 / 12) 24.77% (27 / 109)
node-npmtest-azure-storage/node_modules/azure-storage/lib/common/http/ 25.86% (30 / 116) 0% (0 / 57) 0% (0 / 22) 25.86% (30 / 116)
node-npmtest-azure-storage/node_modules/azure-storage/lib/common/md5-wrapper/ 80% (4 / 5) 100% (0 / 0) 0% (0 / 2) 80% (4 / 5)
node-npmtest-azure-storage/node_modules/azure-storage/lib/common/models/ 11.98% (26 / 217) 0% (0 / 147) 0% (0 / 17) 11.98% (26 / 217)
node-npmtest-azure-storage/node_modules/azure-storage/lib/common/services/ 16.69% (128 / 767) 0% (0 / 426) 2% (2 / 100) 16.78% (128 / 763)
node-npmtest-azure-storage/node_modules/azure-storage/lib/common/signing/ 15.2% (31 / 204) 0% (0 / 127) 0% (0 / 25) 15.27% (31 / 203)
node-npmtest-azure-storage/node_modules/azure-storage/lib/common/streams/ 17.61% (140 / 795) 0.3% (1 / 337) 0% (0 / 99) 17.9% (140 / 782)
node-npmtest-azure-storage/node_modules/azure-storage/lib/common/util/ 22.29% (115 / 516) 1.26% (3 / 239) 0.96% (1 / 104) 22.37% (115 / 514)
node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/ 7.47% (142 / 1901) 0% (0 / 614) 0% (0 / 345) 7.98% (142 / 1779)
node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/internal/ 15.65% (18 / 115) 0% (0 / 49) 0% (0 / 11) 15.79% (18 / 114)
node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/models/ 18.18% (32 / 176) 0% (0 / 92) 0% (0 / 22) 18.18% (32 / 176)
node-npmtest-azure-storage/node_modules/azure-storage/lib/services/file/ 6.96% (102 / 1465) 0% (0 / 368) 0% (0 / 267) 7.45% (102 / 1370)
node-npmtest-azure-storage/node_modules/azure-storage/lib/services/file/internal/ 33.33% (6 / 18) 0% (0 / 4) 0% (0 / 1) 33.33% (6 / 18)
node-npmtest-azure-storage/node_modules/azure-storage/lib/services/file/models/ 23.58% (25 / 106) 0% (0 / 40) 0% (0 / 17) 23.58% (25 / 106)
node-npmtest-azure-storage/node_modules/azure-storage/lib/services/queue/ 13.44% (70 / 521) 0% (0 / 116) 0% (0 / 118) 14.55% (70 / 481)
node-npmtest-azure-storage/node_modules/azure-storage/lib/services/queue/models/ 24.62% (16 / 65) 0% (0 / 36) 0% (0 / 9) 24.62% (16 / 65)
node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/ 18.96% (109 / 575) 0% (0 / 159) 0.79% (1 / 126) 19.78% (109 / 551)
node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/internal/ 21.07% (51 / 242) 0% (0 / 164) 0% (0 / 18) 21.07% (51 / 242)
node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/models/ 23.19% (32 / 138) 0% (0 / 60) 0% (0 / 17) 23.19% (32 / 138)
Code coverage report for node-npmtest-azure-storage/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/

Statements: 100% (153 / 153)      Branches: 100% (126 / 126)      Functions: 100% (28 / 28)      Lines: 100% (153 / 153)      Ignored: 26 statements, 1 function, 30 branches     

All files » node-npmtest-azure-storage/
File Statements Branches Functions Lines
example.js 100% (83 / 83) 100% (73 / 73) 100% (12 / 12) 100% (83 / 83)
lib.npmtest_azure_storage.js 100% (16 / 16) 100% (14 / 14) 100% (3 / 3) 100% (16 / 16)
test.js 100% (54 / 54) 100% (39 / 39) 100% (13 / 13) 100% (54 / 54)
Code coverage report for node-npmtest-azure-storage/example.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/example.js

Statements: 100% (83 / 83)      Branches: 100% (73 / 73)      Functions: 100% (12 / 12)      Lines: 100% (83 / 83)      Ignored: 26 statements, 1 function, 30 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328                                                  2   2         2   2   2 2 2         1             2       2       2   2               1 2           2     2     2 2   1       2     1 1 1   1 1     1 1   1     1   2           1   1   1         1 2 2 3 3 3 3 1     3 3         3       1 3 1       1 1               1   1 1 1   1   1                                                                                                                                                                                       1 1                       1     6 6   1   2   1   2         1 1   1         1             1     1 1     1 1   1 1 1 1 1 1 1   1 1   1        
/*
example.js
 
quickstart example
 
instruction
    1. save this script as example.js
    2. run the shell command:
        $ npm install npmtest-azure-storage && PORT=8081 node example.js
    3. play with the browser-demo on http://127.0.0.1:8081
*/
 
 
 
/* istanbul instrument in package npmtest_azure_storage */
/*jslint
    bitwise: true,
    browser: true,
    maxerr: 8,
    maxlen: 96,
    node: true,
    nomen: true,
    regexp: true,
    stupid: true
*/
(function () {
    'use strict';
    var local;
 
 
 
    // run shared js-env code - pre-init
    (function () {
        // init local
        local = {};
        // init modeJs
        local.modeJs = (function () {
            try {
                return typeof navigator.userAgent === 'string' &&
                    typeof document.querySelector('body') === 'object' &&
                    typeof XMLHttpRequest.prototype.open === 'function' &&
                    'browser';
            } catch (errorCaughtBrowser) {
                return module.exports &&
                    typeof process.versions.node === 'string' &&
                    typeof require('http').createServer === 'function' &&
                    'node';
            }
        }());
        // init global
        local.global = local.modeJs === 'browser'
            ? window
            : global;
        // init utility2_rollup
        local = local.global.utility2_rollup || (local.modeJs === 'browser'
            ? local.global.utility2_npmtest_azure_storage
            : global.utility2_moduleExports);
        // export local
        local.global.local = local;
    }());
    switch (local.modeJs) {
 
 
 
    // post-init
    // run browser js-env code - post-init
    /* istanbul ignore next */
    case 'browser':
        local.testRunBrowser = function (event) {
            Eif (!event || (event &&
                    event.currentTarget &&
                    event.currentTarget.className &&
                    event.currentTarget.className.includes &&
                    event.currentTarget.className.includes('onreset'))) {
                // reset output
                Array.from(
                    document.querySelectorAll('body > .resettable')
                ).forEach(function (element) {
                    switch (element.tagName) {
                    case 'INPUT':
                    case 'TEXTAREA':
                        element.value = '';
                        break;
                    default:
                        element.textContent = '';
                    }
                });
            }
            switch (event && event.currentTarget && event.currentTarget.id) {
            case 'testRunButton1':
                // show tests
                Eif (document.querySelector('#testReportDiv1').style.display === 'none') {
                    document.querySelector('#testReportDiv1').style.display = 'block';
                    document.querySelector('#testRunButton1').textContent =
                        'hide internal test';
                    local.modeTest = true;
                    local.testRunDefault(local);
                // hide tests
                } else {
                    document.querySelector('#testReportDiv1').style.display = 'none';
                    document.querySelector('#testRunButton1').textContent = 'run internal test';
                }
                break;
            // custom-case
            default:
                break;
            }
            Iif (document.querySelector('#inputTextareaEval1') && (!event || (event &&
                    event.currentTarget &&
                    event.currentTarget.className &&
                    event.currentTarget.className.includes &&
                    event.currentTarget.className.includes('oneval')))) {
                // try to eval input-code
                try {
                    /*jslint evil: true*/
                    eval(document.querySelector('#inputTextareaEval1').value);
                } catch (errorCaught) {
                    console.error(errorCaught);
                }
            }
        };
        // log stderr and stdout to #outputTextareaStdout1
        ['error', 'log'].forEach(function (key) {
            console[key + '_original'] = console[key];
            console[key] = function () {
                var element;
                console[key + '_original'].apply(console, arguments);
                element = document.querySelector('#outputTextareaStdout1');
                Iif (!element) {
                    return;
                }
                // append text to #outputTextareaStdout1
                element.value += Array.from(arguments).map(function (arg) {
                    return typeof arg === 'string'
                        ? arg
                        : JSON.stringify(arg, null, 4);
                }).join(' ') + '\n';
                // scroll textarea to bottom
                element.scrollTop = element.scrollHeight;
            };
        });
        // init event-handling
        ['change', 'click', 'keyup'].forEach(function (event) {
            Array.from(document.querySelectorAll('.on' + event)).forEach(function (element) {
                element.addEventListener(event, local.testRunBrowser);
            });
        });
        // run tests
        local.testRunBrowser();
        break;
 
 
 
    // run node js-env code - post-init
    /* istanbul ignore next */
    case 'node':
        // export local
        module.exports = local;
        // require modules
        local.fs = require('fs');
        local.http = require('http');
        local.url = require('url');
        // init assets
        local.assetsDict = local.assetsDict || {};
        /* jslint-ignore-begin */
        local.assetsDict['/assets.index.template.html'] = '\
<!doctype html>\n\
<html lang="en">\n\
<head>\n\
<meta charset="UTF-8">\n\
<meta name="viewport" content="width=device-width, initial-scale=1">\n\
<title>{{env.npm_package_name}} (v{{env.npm_package_version}})</title>\n\
<style>\n\
/*csslint\n\
    box-sizing: false,\n\
    universal-selector: false\n\
*/\n\
* {\n\
    box-sizing: border-box;\n\
}\n\
body {\n\
    background: #dde;\n\
    font-family: Arial, Helvetica, sans-serif;\n\
    margin: 2rem;\n\
}\n\
body > * {\n\
    margin-bottom: 1rem;\n\
}\n\
.utility2FooterDiv {\n\
    margin-top: 20px;\n\
    text-align: center;\n\
}\n\
</style>\n\
<style>\n\
/*csslint\n\
*/\n\
textarea {\n\
    font-family: monospace;\n\
    height: 10rem;\n\
    width: 100%;\n\
}\n\
textarea[readonly] {\n\
    background: #ddd;\n\
}\n\
</style>\n\
</head>\n\
<body>\n\
<!-- utility2-comment\n\
<div id="ajaxProgressDiv1" style="background: #d00; height: 2px; left: 0; margin: 0; padding: 0; position: fixed; top: 0; transition: background 0.5s, width 1.5s; width: 25%;"></div>\n\
utility2-comment -->\n\
<h1>\n\
<!-- utility2-comment\n\
    <a\n\
        {{#if env.npm_package_homepage}}\n\
        href="{{env.npm_package_homepage}}"\n\
        {{/if env.npm_package_homepage}}\n\
        target="_blank"\n\
    >\n\
utility2-comment -->\n\
        {{env.npm_package_name}} (v{{env.npm_package_version}})\n\
<!-- utility2-comment\n\
    </a>\n\
utility2-comment -->\n\
</h1>\n\
<h3>{{env.npm_package_description}}</h3>\n\
<!-- utility2-comment\n\
<h4><a download href="assets.app.js">download standalone app</a></h4>\n\
<button class="onclick onreset" id="testRunButton1">run internal test</button><br>\n\
<div id="testReportDiv1" style="display: none;"></div>\n\
utility2-comment -->\n\
\n\
\n\
\n\
<label>stderr and stdout</label>\n\
<textarea class="resettable" id="outputTextareaStdout1" readonly></textarea>\n\
<!-- utility2-comment\n\
{{#if isRollup}}\n\
<script src="assets.app.js"></script>\n\
{{#unless isRollup}}\n\
utility2-comment -->\n\
<script src="assets.utility2.rollup.js"></script>\n\
<script src="jsonp.utility2._stateInit?callback=window.utility2._stateInit"></script>\n\
<script src="assets.npmtest_azure_storage.rollup.js"></script>\n\
<script src="assets.example.js"></script>\n\
<script src="assets.test.js"></script>\n\
<!-- utility2-comment\n\
{{/if isRollup}}\n\
utility2-comment -->\n\
<div class="utility2FooterDiv">\n\
    [ this app was created with\n\
    <a href="https://github.com/kaizhu256/node-utility2" target="_blank">utility2</a>\n\
    ]\n\
</div>\n\
</body>\n\
</html>\n\
';
        /* jslint-ignore-end */
        Iif (local.templateRender) {
            local.assetsDict['/'] = local.templateRender(
                local.assetsDict['/assets.index.template.html'],
                {
                    env: local.objectSetDefault(local.env, {
                        npm_package_description: 'the greatest app in the world!',
                        npm_package_name: 'my-app',
                        npm_package_nameAlias: 'my_app',
                        npm_package_version: '0.0.1'
                    })
                }
            );
        } else {
            local.assetsDict['/'] = local.assetsDict['/assets.index.template.html']
                .replace((/\{\{env\.(\w+?)\}\}/g), function (match0, match1) {
                    // jslint-hack
                    String(match0);
                    switch (match1) {
                    case 'npm_package_description':
                        return 'the greatest app in the world!';
                    case 'npm_package_name':
                        return 'my-app';
                    case 'npm_package_nameAlias':
                        return 'my_app';
                    case 'npm_package_version':
                        return '0.0.1';
                    }
                });
        }
        // run the cli
        Eif (local.global.utility2_rollup || module !== require.main) {
            break;
        }
        local.assetsDict['/assets.example.js'] =
            local.assetsDict['/assets.example.js'] ||
            local.fs.readFileSync(__filename, 'utf8');
        // bug-workaround - long $npm_package_buildCustomOrg
        /* jslint-ignore-begin */
        local.assetsDict['/assets.npmtest_azure_storage.rollup.js'] =
            local.assetsDict['/assets.npmtest_azure_storage.rollup.js'] ||
            local.fs.readFileSync(
                local.npmtest_azure_storage.__dirname + '/lib.npmtest_azure_storage.js',
                'utf8'
            ).replace((/^#!/), '//');
        /* jslint-ignore-end */
        local.assetsDict['/favicon.ico'] = local.assetsDict['/favicon.ico'] || '';
        // if $npm_config_timeout_exit exists,
        // then exit this process after $npm_config_timeout_exit ms
        if (Number(process.env.npm_config_timeout_exit)) {
            setTimeout(process.exit, Number(process.env.npm_config_timeout_exit));
        }
        // start server
        if (local.global.utility2_serverHttp1) {
            break;
        }
        process.env.PORT = process.env.PORT || '8081';
        console.error('server starting on port ' + process.env.PORT);
        local.http.createServer(function (request, response) {
            request.urlParsed = local.url.parse(request.url);
            if (local.assetsDict[request.urlParsed.pathname] !== undefined) {
                response.end(local.assetsDict[request.urlParsed.pathname]);
                return;
            }
            response.statusCode = 404;
            response.end();
        }).listen(process.env.PORT);
        break;
    }
}());
 
 
Code coverage report for node-npmtest-azure-storage/lib.npmtest_azure_storage.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/lib.npmtest_azure_storage.js

Statements: 100% (16 / 16)      Branches: 100% (14 / 14)      Functions: 100% (3 / 3)      Lines: 100% (16 / 16)      Ignored: none     

All files » node-npmtest-azure-storage/ » lib.npmtest_azure_storage.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55                      2   2         2   2   2 2 2         1             2       2   2   2 1   1 1 1          
/* istanbul instrument in package npmtest_azure_storage */
/*jslint
    bitwise: true,
    browser: true,
    maxerr: 8,
    maxlen: 96,
    node: true,
    nomen: true,
    regexp: true,
    stupid: true
*/
(function () {
    'use strict';
    var local;
 
 
 
    // run shared js-env code - pre-init
    (function () {
        // init local
        local = {};
        // init modeJs
        local.modeJs = (function () {
            try {
                return typeof navigator.userAgent === 'string' &&
                    typeof document.querySelector('body') === 'object' &&
                    typeof XMLHttpRequest.prototype.open === 'function' &&
                    'browser';
            } catch (errorCaughtBrowser) {
                return module.exports &&
                    typeof process.versions.node === 'string' &&
                    typeof require('http').createServer === 'function' &&
                    'node';
            }
        }());
        // init global
        local.global = local.modeJs === 'browser'
            ? window
            : global;
        // init utility2_rollup
        local = local.global.utility2_rollup || local;
        // init lib
        local.local = local.npmtest_azure_storage = local;
        // init exports
        if (local.modeJs === 'browser') {
            local.global.utility2_npmtest_azure_storage = local;
        } else {
            module.exports = local;
            module.exports.__dirname = __dirname;
            module.exports.module = module;
        }
    }());
}());
 
 
Code coverage report for node-npmtest-azure-storage/test.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/test.js

Statements: 100% (54 / 54)      Branches: 100% (39 / 39)      Functions: 100% (13 / 13)      Lines: 100% (54 / 54)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197                      2   2         2   2   2 2 2         1             2     2     1       1     1   1     2           2 2   2           1           1           2 2   2           1             1       1     1             1             1 1     1             1 1 1 1 1 1     1         2 2     1             2 2     1             2 2     1             2 2     1             1 1       1 1        
/* istanbul instrument in package npmtest_azure_storage */
/*jslint
    bitwise: true,
    browser: true,
    maxerr: 8,
    maxlen: 96,
    node: true,
    nomen: true,
    regexp: true,
    stupid: true
*/
(function () {
    'use strict';
    var local;
 
 
 
    // run shared js-env code - pre-init
    (function () {
        // init local
        local = {};
        // init modeJs
        local.modeJs = (function () {
            try {
                return typeof navigator.userAgent === 'string' &&
                    typeof document.querySelector('body') === 'object' &&
                    typeof XMLHttpRequest.prototype.open === 'function' &&
                    'browser';
            } catch (errorCaughtBrowser) {
                return module.exports &&
                    typeof process.versions.node === 'string' &&
                    typeof require('http').createServer === 'function' &&
                    'node';
            }
        }());
        // init global
        local.global = local.modeJs === 'browser'
            ? window
            : global;
        switch (local.modeJs) {
        // re-init local from window.local
        case 'browser':
            local = local.global.utility2.objectSetDefault(
                local.global.utility2_rollup || local.global.local,
                local.global.utility2
            );
            break;
        // re-init local from example.js
        case 'node':
            local = (local.global.utility2_rollup || require('utility2'))
                .requireExampleJsFromReadme();
            break;
        }
        // export local
        local.global.local = local;
    }());
 
 
 
    // run shared js-env code - function
    (function () {
        return;
    }());
    switch (local.modeJs) {
 
 
 
    // run browser js-env code - function
    case 'browser':
        break;
 
 
 
    // run node js-env code - function
    case 'node':
        break;
    }
 
 
 
    // run shared js-env code - post-init
    (function () {
        return;
    }());
    switch (local.modeJs) {
 
 
 
    // run browser js-env code - post-init
    case 'browser':
        local.testCase_browser_nullCase = local.testCase_browser_nullCase || function (
            options,
            onError
        ) {
        /*
         * this function will test browsers's null-case handling-behavior-behavior
         */
            onError(null, options);
        };
 
        // run tests
        local.nop(local.modeTest &&
            document.querySelector('#testRunButton1') &&
            document.querySelector('#testRunButton1').click());
        break;
 
 
 
    // run node js-env code - post-init
    /* istanbul ignore next */
    case 'node':
        local.testCase_buildApidoc_default = local.testCase_buildApidoc_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildApidoc's default handling-behavior-behavior
         */
            options = { modulePathList: module.paths };
            local.buildApidoc(options, onError);
        };
 
        local.testCase_buildApp_default = local.testCase_buildApp_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildApp's default handling-behavior-behavior
         */
            local.testCase_buildReadme_default(options, local.onErrorThrow);
            local.testCase_buildLib_default(options, local.onErrorThrow);
            local.testCase_buildTest_default(options, local.onErrorThrow);
            local.testCase_buildCustomOrg_default(options, local.onErrorThrow);
            options = [];
            local.buildApp(options, onError);
        };
 
        local.testCase_buildCustomOrg_default = local.testCase_buildCustomOrg_default ||
            function (options, onError) {
            /*
             * this function will test buildCustomOrg's default handling-behavior
             */
                options = {};
                local.buildCustomOrg(options, onError);
            };
 
        local.testCase_buildLib_default = local.testCase_buildLib_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildLib's default handling-behavior
         */
            options = {};
            local.buildLib(options, onError);
        };
 
        local.testCase_buildReadme_default = local.testCase_buildReadme_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildReadme's default handling-behavior-behavior
         */
            options = {};
            local.buildReadme(options, onError);
        };
 
        local.testCase_buildTest_default = local.testCase_buildTest_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildTest's default handling-behavior
         */
            options = {};
            local.buildTest(options, onError);
        };
 
        local.testCase_webpage_default = local.testCase_webpage_default || function (
            options,
            onError
        ) {
        /*
         * this function will test webpage's default handling-behavior
         */
            options = { modeCoverageMerge: true, url: local.serverLocalHost + '?modeTest=1' };
            local.browserTest(options, onError);
        };
 
        // run test-server
        local.testRunServer(local);
        break;
    }
}());
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/

Statements: 10% (1 / 10)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 10% (1 / 10)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/
File Statements Branches Functions Lines
gruntfile.js 10% (1 / 10) 100% (0 / 0) 0% (0 / 1) 10% (1 / 10)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/gruntfile.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/gruntfile.js

Statements: 10% (1 / 10)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 10% (1 / 10)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103                                1                                                                                                                                                                            
//
// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
 
module.exports = function(grunt) {
  //init stuff
  grunt.initConfig({
 
    nsp: {
      package: grunt.file.readJSON('package.json')
    },
 
    mochaTest: {
      test: {
        options: {
          reporter: 'spec',
          quiet: false,
          clearRequireCache: false,
          timeout: 100000
        },
        src: ['test/**/*.js']
      }
    },
 
    //jsdoc config
    jsdoc: {
      dist: {
        src: [
          'README.md',
          'lib/azure-storage.js',
          'lib/common/filters/retrypolicyfilter.js',
          'lib/common/filters/linearretrypolicyfilter.js',
          'lib/common/filters/exponentialretrypolicyfilter.js',
          'lib/common/services/storageutilities.js',
          'lib/services/blob/blobservice.js',
          'lib/services/blob/models/blobresult.js',
          'lib/services/blob/models/containerresult.js',
          'lib/services/blob/models/leaseresult.js',
          'lib/services/blob/blobutilities.js',
          'lib/services/queue/queueservice.js',
          'lib/services/queue/queuemessageencoder.js',
          'lib/services/queue/queueutilities.js',
          'lib/services/queue/models/queueresult.js',
          'lib/services/queue/models/queuemessageresult.js',
          'lib/services/table/tableservice.js',
          'lib/services/table/tablebatch.js',
          'lib/services/table/tablequery.js',
          'lib/services/table/tableutilities.js',
          'lib/services/file/fileservice.js',
          'lib/services/file/fileutilities.js',
          'lib/services/file/models/shareresult.js',
          'lib/services/file/models/directoryresult.js',
          'lib/services/file/models/fileresult.js',
          'lib/common/services/storageserviceclient.js',
          'lib/common/diagnostics/logger.js'
        ],
        options: {
          destination: 'docs',
          template: 'node_modules/ink-docstrap/template',
          configure: 'jsdoc/jsdoc.json'
        }
      }
    },
 
    // devserver config
    devserver: {
      server : {},
      options: {
        'base': 'docs'
      }
    },
 
    jshint: {
      all: ['Gruntfile.js', 'lib/**/*.js'],
      options: {
        jshintrc: true
      }
    }
  });
 
  grunt.loadNpmTasks('grunt-jsdoc');
  grunt.loadNpmTasks('grunt-mocha-test');
  grunt.loadNpmTasks('grunt-devserver');
  grunt.loadNpmTasks('grunt-nsp');
  grunt.loadNpmTasks('grunt-contrib-jshint');
 
  grunt.registerTask('doc', ['jsdoc', 'devserver']);
  grunt.registerTask('validate', ['jshint', 'nsp']);
  grunt.registerTask('default', ['validate', 'mochaTest']);
};
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/browser/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/browser/

Statements: 3.36% (5 / 149)      Branches: 22.22% (4 / 18)      Functions: 0% (0 / 17)      Lines: 3.36% (5 / 149)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/browser/
File Statements Branches Functions Lines
azure-storage.blob.export.js 2.86% (1 / 35) 25% (1 / 4) 0% (0 / 5) 2.86% (1 / 35)
azure-storage.file.export.js 3.03% (1 / 33) 25% (1 / 4) 0% (0 / 4) 3.03% (1 / 33)
azure-storage.queue.export.js 2.94% (1 / 34) 25% (1 / 4) 0% (0 / 4) 2.94% (1 / 34)
azure-storage.table.export.js 2.86% (1 / 35) 25% (1 / 4) 0% (0 / 4) 2.86% (1 / 35)
bundle.js 8.33% (1 / 12) 0% (0 / 2) 100% (0 / 0) 8.33% (1 / 12)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/browser/azure-storage.blob.export.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/browser/azure-storage.blob.export.js

Statements: 2.86% (1 / 35)      Branches: 25% (1 / 4)      Functions: 0% (0 / 5)      Lines: 2.86% (1 / 35)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74                                2                                                                                                                  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var AzureStorage = window.AzureStorage || {};
 
AzureStorage.generateDevelopmentStorageCredentials = function (proxyUri) {
  var devStore = 'UseDevelopmentStorage=true;';
  if(proxyUri){
    devStore += 'DevelopmentStorageProxyUri=' + proxyUri;
  }
 
  return devStore;
};
 
var BlobService = require('../lib/services/blob/blobservice');
 
AzureStorage.BlobService = BlobService;
AzureStorage.BlobUtilities = require('../lib/services/blob/blobutilities');
 
AzureStorage.createBlobService = function (storageAccountOrConnectionString, storageAccessKey, host) {
  return new BlobService(storageAccountOrConnectionString, storageAccessKey, host, null);
};
 
AzureStorage.createBlobServiceWithSas = function (host, sasToken) {
  return new BlobService(null, null, host, sasToken);
};
 
AzureStorage.createBlobServiceAnonymous = function (host) {
  return new BlobService(null, null, host, null);
};
 
var azureCommon = require('../lib/common/common');
var StorageServiceClient = azureCommon.StorageServiceClient;
var SharedKey = azureCommon.SharedKey;
 
AzureStorage.generateAccountSharedAccessSignature = function(storageAccountOrConnectionString, storageAccessKey, sharedAccessAccountPolicy)
{
  var storageSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey);
  var sharedKey = new SharedKey(storageSettings._name, storageSettings._key);
  
  return sharedKey.generateAccountSignedQueryString(sharedAccessAccountPolicy);
};
 
AzureStorage.Constants = azureCommon.Constants;
AzureStorage.StorageUtilities = azureCommon.StorageUtilities;
AzureStorage.AccessCondition = azureCommon.AccessCondition;
 
AzureStorage.SR = azureCommon.SR;
AzureStorage.StorageServiceClient = StorageServiceClient;
AzureStorage.Logger = azureCommon.Logger;
AzureStorage.WebResource = azureCommon.WebResource;
AzureStorage.Validate = azureCommon.validate;
AzureStorage.date = azureCommon.date;
 
// Other filters
AzureStorage.LinearRetryPolicyFilter = azureCommon.LinearRetryPolicyFilter;
AzureStorage.ExponentialRetryPolicyFilter = azureCommon.ExponentialRetryPolicyFilter;
AzureStorage.RetryPolicyFilter = azureCommon.RetryPolicyFilter;
 
window.AzureStorage = AzureStorage;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/browser/azure-storage.file.export.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/browser/azure-storage.file.export.js

Statements: 3.03% (1 / 33)      Branches: 25% (1 / 4)      Functions: 0% (0 / 4)      Lines: 3.03% (1 / 33)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70                                2                                                                                                          
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var AzureStorage = window.AzureStorage || {};
 
AzureStorage.generateDevelopmentStorageCredentials = function (proxyUri) {
  var devStore = 'UseDevelopmentStorage=true;';
  if(proxyUri){
    devStore += 'DevelopmentStorageProxyUri=' + proxyUri;
  }
 
  return devStore;
};
 
var FileService = require('../lib/services/file/fileservice');
 
AzureStorage.FileService = FileService;
AzureStorage.FileUtilities = require('../lib/services/file/fileutilities');
 
AzureStorage.createFileService = function (storageAccountOrConnectionString, storageAccessKey, host) {
  return new FileService(storageAccountOrConnectionString, storageAccessKey, host);
};
 
AzureStorage.createFileServiceWithSas = function (hostUri, sasToken) {
  return new FileService(null, null, hostUri, sasToken);
};
 
var azureCommon = require('../lib/common/common');
var StorageServiceClient = azureCommon.StorageServiceClient;
var SharedKey = azureCommon.SharedKey;
 
AzureStorage.generateAccountSharedAccessSignature = function(storageAccountOrConnectionString, storageAccessKey, sharedAccessAccountPolicy)
{
  var storageSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey);
  var sharedKey = new SharedKey(storageSettings._name, storageSettings._key);
  
  return sharedKey.generateAccountSignedQueryString(sharedAccessAccountPolicy);
};
 
AzureStorage.Constants = azureCommon.Constants;
AzureStorage.StorageUtilities = azureCommon.StorageUtilities;
AzureStorage.AccessCondition = azureCommon.AccessCondition;
 
AzureStorage.SR = azureCommon.SR;
AzureStorage.StorageServiceClient = StorageServiceClient;
AzureStorage.Logger = azureCommon.Logger;
AzureStorage.WebResource = azureCommon.WebResource;
AzureStorage.Validate = azureCommon.validate;
AzureStorage.date = azureCommon.date;
 
// Other filters
AzureStorage.LinearRetryPolicyFilter = azureCommon.LinearRetryPolicyFilter;
AzureStorage.ExponentialRetryPolicyFilter = azureCommon.ExponentialRetryPolicyFilter;
AzureStorage.RetryPolicyFilter = azureCommon.RetryPolicyFilter;
 
window.AzureStorage = AzureStorage;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/browser/azure-storage.queue.export.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/browser/azure-storage.queue.export.js

Statements: 2.94% (1 / 34)      Branches: 25% (1 / 4)      Functions: 0% (0 / 4)      Lines: 2.94% (1 / 34)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71                                2                                                                                                            
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var AzureStorage = window.AzureStorage || {};
 
AzureStorage.generateDevelopmentStorageCredentials = function (proxyUri) {
  var devStore = 'UseDevelopmentStorage=true;';
  if(proxyUri){
    devStore += 'DevelopmentStorageProxyUri=' + proxyUri;
  }
 
  return devStore;
};
 
var QueueService = require('../lib/services/queue/queueservice');
 
AzureStorage.QueueService = QueueService;
AzureStorage.QueueUtilities = require('../lib/services/queue/queueutilities');
AzureStorage.QueueMessageEncoder = require('../lib/services/queue/queuemessageencoder');
 
AzureStorage.createQueueService = function (storageAccountOrConnectionString, storageAccessKey, host) {
  return new QueueService(storageAccountOrConnectionString, storageAccessKey, host);
};
 
AzureStorage.createQueueServiceWithSas = function(hostUri, sasToken) {
  return new QueueService(null, null, hostUri, sasToken);
};
 
var azureCommon = require('../lib/common/common');
var StorageServiceClient = azureCommon.StorageServiceClient;
var SharedKey = azureCommon.SharedKey;
 
AzureStorage.generateAccountSharedAccessSignature = function(storageAccountOrConnectionString, storageAccessKey, sharedAccessAccountPolicy)
{
  var storageSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey);
  var sharedKey = new SharedKey(storageSettings._name, storageSettings._key);
  
  return sharedKey.generateAccountSignedQueryString(sharedAccessAccountPolicy);
};
 
AzureStorage.Constants = azureCommon.Constants;
AzureStorage.StorageUtilities = azureCommon.StorageUtilities;
AzureStorage.AccessCondition = azureCommon.AccessCondition;
 
AzureStorage.SR = azureCommon.SR;
AzureStorage.StorageServiceClient = StorageServiceClient;
AzureStorage.Logger = azureCommon.Logger;
AzureStorage.WebResource = azureCommon.WebResource;
AzureStorage.Validate = azureCommon.validate;
AzureStorage.date = azureCommon.date;
 
// Other filters
AzureStorage.LinearRetryPolicyFilter = azureCommon.LinearRetryPolicyFilter;
AzureStorage.ExponentialRetryPolicyFilter = azureCommon.ExponentialRetryPolicyFilter;
AzureStorage.RetryPolicyFilter = azureCommon.RetryPolicyFilter;
 
window.AzureStorage = AzureStorage;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/browser/azure-storage.table.export.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/browser/azure-storage.table.export.js

Statements: 2.86% (1 / 35)      Branches: 25% (1 / 4)      Functions: 0% (0 / 4)      Lines: 2.86% (1 / 35)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71                                2                                                                                                            
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var AzureStorage = window.AzureStorage || {};
 
AzureStorage.generateDevelopmentStorageCredentials = function (proxyUri) {
  var devStore = 'UseDevelopmentStorage=true;';
  if(proxyUri){
    devStore += 'DevelopmentStorageProxyUri=' + proxyUri;
  }
 
  return devStore;
};
 
var TableService = require('../lib/services/table/tableservice');
AzureStorage.TableService = TableService;
AzureStorage.TableQuery = require('../lib/services/table/tablequery');
AzureStorage.TableBatch = require('../lib/services/table/tablebatch');
AzureStorage.TableUtilities = require('../lib/services/table/tableutilities');
 
AzureStorage.createTableService = function (storageAccountOrConnectionString, storageAccessKey, host) {
  return new TableService(storageAccountOrConnectionString, storageAccessKey, host);
};
 
AzureStorage.createTableServiceWithSas = function (hostUri, sasToken) {
  return new TableService(null, null, hostUri, sasToken);
};
 
var azureCommon = require('../lib/common/common');
var StorageServiceClient = azureCommon.StorageServiceClient;
var SharedKey = azureCommon.SharedKey;
 
AzureStorage.generateAccountSharedAccessSignature = function(storageAccountOrConnectionString, storageAccessKey, sharedAccessAccountPolicy)
{
  var storageSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey);
  var sharedKey = new SharedKey(storageSettings._name, storageSettings._key);
  
  return sharedKey.generateAccountSignedQueryString(sharedAccessAccountPolicy);
};
 
AzureStorage.Constants = azureCommon.Constants;
AzureStorage.StorageUtilities = azureCommon.StorageUtilities;
AzureStorage.AccessCondition = azureCommon.AccessCondition;
 
AzureStorage.SR = azureCommon.SR;
AzureStorage.StorageServiceClient = StorageServiceClient;
AzureStorage.Logger = azureCommon.Logger;
AzureStorage.WebResource = azureCommon.WebResource;
AzureStorage.Validate = azureCommon.validate;
AzureStorage.date = azureCommon.date;
 
// Other filters
AzureStorage.LinearRetryPolicyFilter = azureCommon.LinearRetryPolicyFilter;
AzureStorage.ExponentialRetryPolicyFilter = azureCommon.ExponentialRetryPolicyFilter;
AzureStorage.RetryPolicyFilter = azureCommon.RetryPolicyFilter;
 
window.AzureStorage = AzureStorage;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/browser/bundle.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/browser/bundle.js

Statements: 8.33% (1 / 12)      Branches: 0% (0 / 2)      Functions: 100% (0 / 0)      Lines: 8.33% (1 / 12)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51                                2                                                                    
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var browserify = require('browserify');
var factor = require('factor-bundle');
var fs = require('fs');
var path = require('path');
 
var outputFolder = 'bundle';
var outputFolderPath = path.resolve(__dirname, outputFolder);
 
console.log('Generating Azure Storage JavaScript Client Library to ' + outputFolderPath + ' ...\n');
 
if (!fs.existsSync(outputFolderPath)) {
    fs.mkdirSync(outputFolderPath);
}
 
var b = browserify([
    path.resolve(__dirname, 'azure-storage.blob.export.js'),
    path.resolve(__dirname, 'azure-storage.file.export.js'),
    path.resolve(__dirname, 'azure-storage.queue.export.js'),
    path.resolve(__dirname, 'azure-storage.table.export.js')
], {require: ['stream', 'util', 'buffer']});
 
b.plugin(factor, {
    outputs: [
        path.resolve(outputFolderPath, 'azure-storage.blob.js'),
        path.resolve(outputFolderPath, 'azure-storage.file.js'),
        path.resolve(outputFolderPath, 'azure-storage.queue.js'),
        path.resolve(outputFolderPath, 'azure-storage.table.js')
    ] 
});
 
b.bundle().pipe(
    fs.createWriteStream(path.resolve(outputFolderPath, 'azure-storage.common.js'))
);
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/

Statements: 72.41% (42 / 58)      Branches: 0% (0 / 2)      Functions: 0% (0 / 11)      Lines: 72.41% (42 / 58)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/lib/
File Statements Branches Functions Lines
azure-storage.js 72.41% (42 / 58) 0% (0 / 2) 0% (0 / 11) 72.41% (42 / 58)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/azure-storage.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/azure-storage.js

Statements: 72.41% (42 / 58)      Branches: 0% (0 / 2)      Functions: 0% (0 / 11)      Lines: 72.41% (42 / 58)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371                                1                       1                         1   1 1 1 1                           1                       1               1   1 1                         1                       1                     1               1   1 1                         1                       1               1   1 1 1                         1                       1                   1 1 1                                   1                                                                                                                                                                                                                                                                         1 1 1   1 1 1 1 1 1     1 1 1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var exports = module.exports;
 
/**
* Creates a connection string that can be used to create a service which runs on the storage emulator. The emulator must be downloaded separately.
*
* @param {string}   [proxyUri]                  The proxyUri. By default, http://127.0.0.1
* @return {string}                              A connection string representing the development storage credentials.
* @example
* var azure = require('azure-storage');
* var devStoreCreds = azure.generateDevelopmentStorageCredentials();
* var blobService = azure.createBlobService(devStoreCreds);
*/
exports.generateDevelopmentStorageCredentials = function (proxyUri) {
  var devStore = 'UseDevelopmentStorage=true;';
  if(proxyUri){
    devStore += 'DevelopmentStorageProxyUri=' + proxyUri;
  }
 
  return devStore;
};
 
/**
 * Table client exports.
 * @ignore
 */
var TableService = require('./services/table/tableservice');
 
exports.TableService = TableService;
exports.TableQuery = require('./services/table/tablequery');
exports.TableBatch = require('./services/table/tablebatch');
exports.TableUtilities = require('./services/table/tableutilities');
 
/**
* Creates a new {@link TableService} object.
* If no storageaccount or storageaccesskey are provided, the AZURE_STORAGE_CONNECTION_STRING and then the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY 
* environment variables will be used.
*
* @param {string} [storageAccountOrConnectionString]  The storage account or the connection string.
* @param {string} [storageAccessKey]                  The storage access key.
* @param {string|object} [host]                       The host address. To define primary only, pass a string. 
*                                                     Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host.
* @return {TableService}                              A new TableService object.
*
*/
exports.createTableService = function (storageAccountOrConnectionString, storageAccessKey, host) {
  return new TableService(storageAccountOrConnectionString, storageAccessKey, host);
};
 
/**
* Creates a new {@link TableService} object using the host Uri and the SAS credentials provided.
* 
* @param {string|object} host                         The host address. To define primary only, pass a string. 
*                                                     Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host.
* @param {string} sasToken                            The Shared Access Signature token.
* @return {TableService}                              A new TableService object with the SAS credentials.
*/
exports.createTableServiceWithSas = function (hostUri, sasToken) {
  return new TableService(null, null, hostUri, sasToken);
};
 
/**
 * Blob client exports.
 * @ignore
 */
var BlobService = require('./services/blob/blobservice');
 
exports.BlobService = BlobService;
exports.BlobUtilities = require('./services/blob/blobutilities');
 
/**
* Creates a new {@link BlobService} object.
* If no storageaccount or storageaccesskey are provided, the AZURE_STORAGE_CONNECTION_STRING and then the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY 
* environment variables will be used.
*
* @param {string} storageAccountOrConnectionString    The storage account or the connection string.
* @param {string} [storageAccessKey]                  The storage access key.
* @param {string|object} [host]                       The host address. To define primary only, pass a string. 
*                                                     Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host.
* @return {BlobService}                               A new BlobService object.
*/
exports.createBlobService = function (storageAccountOrConnectionString, storageAccessKey, host) {
  return new BlobService(storageAccountOrConnectionString, storageAccessKey, host, null);
};
 
/**
* Creates a new {@link BlobService} object using the host Uri and the SAS credentials provided.
* 
* @param {string|object} host                         The host address. To define primary only, pass a string. 
*                                                     Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host.
* @param {string} sasToken                            The Shared Access Signature token.
* @return {BlobService}                               A new BlobService object with the SAS credentials.
*/
exports.createBlobServiceWithSas = function (host, sasToken) {
  return new BlobService(null, null, host, sasToken);
};
 
/**
* Creates a new {@link BlobService} object using the host uri and anonymous access.
* 
* @param {string|object} host                         The host address. To define primary only, pass a string. 
*                                                     Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host.
* @return {BlobService}                               A new BlobService object with the anonymous credentials.
*/
exports.createBlobServiceAnonymous = function (host) {
  return new BlobService(null, null, host, null);
};
 
/**
 * File client exports.
 * @ignore
 */
var FileService = require('./services/file/fileservice');
 
exports.FileService = FileService;
exports.FileUtilities = require('./services/file/fileutilities');
 
/**
* Creates a new {@link FileService} object.
* If no storageaccount or storageaccesskey are provided, the AZURE_STORAGE_CONNECTION_STRING and then the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY 
* environment variables will be used.
*
* @param {string} storageAccountOrConnectionString    The storage account or the connection string.
* @param {string} [storageAccessKey]                  The storage access key.
* @param {string|object} [host]                       The host address. To define primary only, pass a string. 
*                                                     Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host.
* @return {FileService}                               A new FileService object.
*/
exports.createFileService = function (storageAccountOrConnectionString, storageAccessKey, host) {
  return new FileService(storageAccountOrConnectionString, storageAccessKey, host);
};
 
/**
* Creates a new {@link FileService} object using the host Uri and the SAS credentials provided.
* 
* @param {string|object} host                         The host address. To define primary only, pass a string. 
*                                                     Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host.
* @param {string} sasToken                            The Shared Access Signature token.
* @return {FileService}                               A new FileService object with the SAS credentials.
*/
exports.createFileServiceWithSas = function (hostUri, sasToken) {
  return new FileService(null, null, hostUri, sasToken);
};
 
/**
 * Queue client exports.
 * @ignore
 */
var QueueService = require('./services/queue/queueservice');
 
exports.QueueService = QueueService;
exports.QueueUtilities = require('./services/queue/queueutilities');
exports.QueueMessageEncoder = require('./services/queue/queuemessageencoder');
 
/**
* Creates a new {@link QueueService} object.
* If no storageaccount or storageaccesskey are provided, the AZURE_STORAGE_CONNECTION_STRING and then the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY 
* environment variables will be used.
*
* @param {string} [storageAccountOrConnectionString]  The storage account or the connection string.
* @param {string} [storageAccessKey]                  The storage access key.
* @param {string|object} [host]                       The host address. To define primary only, pass a string. 
*                                                     Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host.
* @return {QueueService}                              A new QueueService object.
*/
exports.createQueueService = function (storageAccountOrConnectionString, storageAccessKey, host) {
  return new QueueService(storageAccountOrConnectionString, storageAccessKey, host);
};
 
/**
* Creates a new {@link QueueService} object using the host Uri and the SAS credentials provided.
* 
* @param {string|object} host                         The host address. To define primary only, pass a string. 
*                                                     Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host.
* @param {string} sasToken                            The Shared Access Signature token.
* @return {QueueService}                              A new QueueService object with the SAS credentials.
*/
exports.createQueueServiceWithSas = function(hostUri, sasToken) {
  return new QueueService(null, null, hostUri, sasToken);
};
 
/**
* Account SAS
* @ignore
*/
 
 
var azureCommon = require('./common/common');
var StorageServiceClient = azureCommon.StorageServiceClient;
var SharedKey = azureCommon.SharedKey;
/**
* Generates an account shared access signature token
* 
* @param {string}                     [storageAccountOrConnectionString]                The storage account or the connection string.
* @param {string}                     [storageAccessKey]                                The storage access key.
* @param {object}                     sharedAccessPolicy                                The shared access policy.
* @param {SharedAccessServices}       sharedAccessPolicy.AccessPolicy.Services          The services (blob, file, queue, table) for a shared access signature associated with this shared access policy.
*                                                                                       Refer to `Constants.AccountSasConstants.Services`.
* @param {SharedAccessResourceTypes}  sharedAccessPolicy.AccessPolicy.ResourceTypes     The resource type for a shared access signature associated with this shared access policy.
*                                                                                       Refer to `Constants.AccountSasConstants.ResourceTypes`.
* @param {SharedAccessPermissions}    sharedAccessPolicy.AccessPolicy.Permissions       The permissions for a shared access signature. 
*                                                                                       Refer to `Constants.AccountSasConstants.Permissions`.
* @param {date}                       sharedAccessPolicy.AccessPolicy.Start             The time at which the Shared Access Signature becomes valid.
* @param {date}                       sharedAccessPolicy.AccessPolicy.Expiry            The time at which the Shared Access Signature becomes expired.
* @param {string}                     sharedAccessPolicy.AccessPolicy.IPAddressOrRange  The permission type. Refer to `Constants.AccountSasConstants.ResourceTypes`.
* @param {string}                     sharedAccessPolicy.AccessPolicy.Protocols          The possible protocols. Refer to `Constants.AccountSasConstants.ResourceTypes`.
*/
exports.generateAccountSharedAccessSignature = function(storageAccountOrConnectionString, storageAccessKey, sharedAccessAccountPolicy)
{
  var storageSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey);
  var sharedKey = new SharedKey(storageSettings._name, storageSettings._key);
  
  return sharedKey.generateAccountSignedQueryString(sharedAccessAccountPolicy);
};
 
 
/**
* A callback that returns a response object.
* @callback errorOrResponse
* @param {object} error         If an error occurs, will contain information about the error.
* @param {object} response      Contains information about the response returned for the operation.
*                               For example, HTTP status codes and headers.
*/
 
/**
* A callback that returns result and response objects.
* @callback errorOrResult
* @param {object} error         If an error occurs, will contain information about the error.
* @param {object} result        The result of the operation.
* @param {object} response      Contains information about the response returned for the operation.
*                               For example, HTTP status codes and headers.
*/
 
 
/**
* Specifying conditional headers for blob service operations. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information.
* @typedef    {object}          AccessConditions
* @property   {string}          EtagMatch                       If the ETag for the blob matches the specified ETag.
*                                                               Specify the wildcard character (*) to perform the operation only if the resource does exist, and fail the operation if it does not exist.
* @property   {string}          EtagNonMatch                    If the ETag for the blob does not match the specified ETag.
*                                                               Specify the wildcard character (*) to perform the operation only if the resource does not exist, and fail the operation if it does exist.
* @property   {Date|string}     DateModifedSince                If the blob has been modified since the specified date.
* @property   {Date|string}     DateUnModifiedSince             If the blob has not been modified since the specified date.
* @property   {Number|string}   SequenceNumberLessThanOrEqual   If the blob's sequence number is less than or equal to the specified value.
*                                                               For Put Page operation only. See https://msdn.microsoft.com/en-us/library/azure/ee691975.aspx for more information.
* @property   {Number|string}   SequenceNumberLessThan          If the blob's sequence number is less than the specified value.
*                                                               For Put Page operation only. See https://msdn.microsoft.com/en-us/library/azure/ee691975.aspx for more information.
* @property   {Number|string}   SequenceNumberEqual             If the blob's sequence number is equal to the specified value.
*                                                               For Put Page operation only. See https://msdn.microsoft.com/en-us/library/azure/ee691975.aspx for more information.
* @property   {Number|string}   MaxBlobSize                     If the Append Block operation would cause the blob to exceed that limit or if the blob size is already greater than the specified value. 
*                                                               For Append Block operation only. See https://msdn.microsoft.com/en-us/library/mt427365.aspx for more information.
* @property   {Number|string}   MaxAppendPosition               If the append position is equal to the specified value.
*                                                               For Append Block operation only. See https://msdn.microsoft.com/en-us/library/mt427365.aspx for more information.
*/
 
/**
* The properties of a storage service, including properties of Storage Analytics and CORS (Cross-Origin Resource Sharing) rules.
* @typedef    {object}              ServiceProperties
* @property   {string}              DefaultServiceVersion  The default version of Storage Analytics currently in use.
* @property   {LoggingProperties}   Logging                The Logging settings.
* @property   {MetricsProperties}   HourMetrics            The HourMetrics settings provide a summary of request statistics grouped by API in hourly aggregates.
* @property   {MetricsProperties}   MinuteMetrics          The HourMetrics settings provide request statistics grouped by API for each minute.
* @property   {object}              Cors                   Groups all CORS rules.
* @property   {CorsRule[]}          Cors.CorsRules         Groups settings for a `[CORS rule]{@link CorsRule}`.
*/
 
/**
* The Azure Analytics logging settings.
* @typedef    {object}          LoggingProperties
* @property   {string}          Version                    The version of Storage Analytics currently in use for logging.
* @property   {boolean}         Delete                     Indicates whether delete requests are being logged.
* @property   {boolean}         Read                       Indicates whether read requests are being logged.
* @property   {boolean}         Write                      Indicates whether write requests are being logged.
* @property   {RetentionPolicy} RetentionPolicy            The retention policy of the log data.
*/
 
/**
* The setting of Azure Analytics summary of request stastics.
* @typedef    {object}          MetricsProperties
* @property   {string}          Version                    The version of Storage Analytics currently in use for hour metrics.
* @property   {string}          Enabled                    Indicates whether metrics are enabled
* @property   {boolean}         IncludeAPIs                Indicates whether metrics generate summary statistics for called API operations.
* @property   {RetentionPolicy} RetentionPolicy            The retention policy of the metrics data.
*/
 
/**
* The CORS rule of a storage service.
* @typedef    {object}          CorsRule
* @property   {string[]}        AllowedMethods             A list of HTTP methods that are allowed to be executed by the origin. For Azure Storage, permitted methods are DELETE, GET, HEAD, MERGE, POST, OPTIONS or PUT.
* @property   {string[]}        AllowedOrigins             A list of origin domains that are allowed via CORS, or "*" if all domains are allowed.
* @property   {string[]}        AllowedHeaders             A list of headers allowed to be part of the cross-origin request.
* @property   {string[]}        ExposedHeaders             A list of response headers to expose to CORS clients.
* @property   {number}          MaxAgeInSeconds            The number of seconds that the client/browser should cache a preflight response.
*/
 
/**
* The Azure Analytics logging or metrics retention policy.
* @typedef    {object}          RetentionPolicy
* @property   {boolean}         Enabled                    Indicates whether a retention policy is enabled for the storage service.
* @property   {number}          Days                       Indicates the number of days that logging data is retained. All data older than this value will be deleted.
*/
 
/**
* The access policy.
* @typedef    {object}          AccessPolicy
* @property   {string}          Permissions                The permission type.
* @property   {Date}            Start                      The time at which the access policy becomes valid.
* @property   {Date}            Expiry                     The time at which the access policy becomes expired.
* @property   {string}          IPAddressOrRange           An IP address or a range of IP addresses from which to accept requests. When specifying a range, note that the range is inclusive.
* @property   {string}          Protocols                  The protocols permitted for a request made with the SAS.
* @property   {string}          Services                   The services (blob, file, queue, table) for a shared access signature associated with this shared access policy.
* @property   {string}          ResourceTypes              The resource type for a shared access signature associated with this shared access policy.
*/
 
/**
* The service statistics.
* @typedef    {object}          ServiceStats
* @property   {object}          GeoReplication                  The geo replication stastics.
* @property   {string}          GeoReplication.Status           The status of the secondary location.
* @property   {Date}            GeoReplication.LastSyncTime     A GMT date/time value, to the second. 
*                                                               All primary writes preceding this value are guaranteed to be available for read operations at the secondary.
*                                                               Primary writes after this point in time may or may not be available for reads. 
*/
 
/**
* The range.
* @typedef    {object}          Range
* @property   {number}          start                     The start of the range.
* @property   {number}          end                       The end of the range.
*/
 
/**
* The range diff. Refer to https://msdn.microsoft.com/en-us/library/azure/mt736912.aspx
* @typedef    {object}          RangeDiff
* @property   {number}          start                     The start of the range.
* @property   {number}          end                       The end of the range.
* @property   {boolean}         isCleared                 If the range is cleared or not.
 
*/
 
exports.Constants = azureCommon.Constants;
exports.StorageUtilities = azureCommon.StorageUtilities;
exports.AccessCondition = azureCommon.AccessCondition;
 
exports.SR = azureCommon.SR;
exports.StorageServiceClient = StorageServiceClient;
exports.Logger = azureCommon.Logger;
exports.WebResource = azureCommon.WebResource;
exports.Validate = azureCommon.validate;
exports.date = azureCommon.date;
 
// Other filters
exports.LinearRetryPolicyFilter = azureCommon.LinearRetryPolicyFilter;
exports.ExponentialRetryPolicyFilter = azureCommon.ExponentialRetryPolicyFilter;
exports.RetryPolicyFilter = azureCommon.RetryPolicyFilter;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/

Statements: 97.06% (33 / 34)      Branches: 25% (2 / 8)      Functions: 100% (0 / 0)      Lines: 97.06% (33 / 34)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/lib/common/
File Statements Branches Functions Lines
common.js 97.06% (33 / 34) 25% (2 / 8) 100% (0 / 0) 97.06% (33 / 34)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/common.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/common.js

Statements: 97.06% (33 / 34)      Branches: 25% (2 / 8)      Functions: 100% (0 / 0)      Lines: 97.06% (33 / 34)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69                                1   1   1   1 1       1 1   1 1     1     1 1 1     1 1 1     1 1     1 1 1 1 1 1 1     1 1 1 1 1 1 1 1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var exports = module.exports;
 
var azureutil = require('./util/util');
 
require('./util/patch-xmlbuilder');
 
var nodeVersion = azureutil.getNodeVersion();
Iif (nodeVersion.major === 0 && nodeVersion.minor > 8 && !(nodeVersion.minor > 10 || (nodeVersion.minor === 10 && nodeVersion.patch >= 3))) {
  throw new Error('The Microsoft Azure node SDK does not work with node versions > 0.9.0 and < 0.10.3. Please upgrade to node >= 0.10.3');
}
 
exports.xmlbuilder = require('xmlbuilder');
exports.xml2js = require('xml2js');
 
exports.Logger = require('./diagnostics/logger');
exports.WebResource = require('./http/webresource');
 
// Services
exports.StorageServiceClient = require('./services/storageserviceclient');
 
// Models
exports.ServicePropertiesResult = require('./models/servicepropertiesresult');
exports.ServiceStatsParser = require('./models/servicestatsparser');
exports.AclResult = require('./models/aclresult');
 
// Filters
exports.LinearRetryPolicyFilter = require('./filters/linearretrypolicyfilter');
exports.ExponentialRetryPolicyFilter = require('./filters/exponentialretrypolicyfilter');
exports.RetryPolicyFilter = require('./filters/retrypolicyfilter');
 
// Signing
exports.SharedAccessSignature = require('./signing/sharedaccesssignature');
exports.SharedKey = require('./signing/sharedkey');
 
// Streams
exports.BatchOperation = require('./streams/batchoperation');
exports.ChunkAllocator = require('./streams/chunkallocator');
exports.ChunkStream = require('./streams/chunkstream');
exports.ChunkStreamWithStream = require('./streams/chunkstreamwithstream');
exports.FileReadStream = require('./streams/filereadstream');
exports.SpeedSummary = require('./streams/speedsummary');
exports.rfs = require('./streams/readablefs');
 
// Utilities
exports.Constants = require('./util/constants');
exports.SR = require('./util/sr');
exports.date = require('./util/date');
exports.ISO8061Date = require('./util/iso8061date');
exports.util = require('./util/util');
exports.validate = require('./util/validate');
exports.StorageUtilities = require('./util/storageutilities');
exports.AccessCondition = require('./util/accesscondition');
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/diagnostics/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/diagnostics/

Statements: 42.42% (14 / 33)      Branches: 0% (0 / 4)      Functions: 0% (0 / 11)      Lines: 42.42% (14 / 33)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/lib/common/diagnostics/
File Statements Branches Functions Lines
logger.js 42.42% (14 / 33) 0% (0 / 4) 0% (0 / 11) 42.42% (14 / 33)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/diagnostics/logger.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/diagnostics/logger.js

Statements: 42.42% (14 / 33)      Branches: 0% (0 / 4)      Functions: 0% (0 / 11)      Lines: 42.42% (14 / 33)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150                                                    1                                           1                                                                                   1                     1       1       1       1       1       1       1       1       1       1                   1    
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
/**
* Creates a new Logger object
* @class
* The Logger class is used to write log information.
* 
* @constructor
*
* @param {string} [level]           The log level. Refer to Logger.LogLevels.
* @param {object} [loggerFunction]  The function to write log information.
*/
function Logger(level, loggerFunction) {
  /**
   * The log level. Refer to the Logger.LogLevels for available log levels. 
   * @name  Logger#level
   * @type  {string}
   * @see Logger.LogLevels
   */
  this.level = level;
  
  this.loggerFunction = loggerFunction;
 
  if (!this.loggerFunction) {
    this.loggerFunction = this.defaultLoggerFunction;
  }
}
 
/**
* The available log levels.
*
* @const
* @enum {string}
*/
Logger.LogLevels = {
  /**
  * System is unusable.
  */
  EMERGENCY: 'emergency',
 
  /**
  * Action must be taken immediately.
  */
  ALERT : 'alert',
 
  /**
  * Critical condition.
  */
  CRITICAL : 'critical',
 
  /**
  * Error condition.
  */
  ERROR : 'error',
 
  /**
  * Warning condition.
  */
  WARNING : 'warning',
 
  /**
  * Normal but significant condition.
  */
  NOTICE : 'notice',
 
  /**
  * Purely informational message.
  */
  INFO : 'info',
 
  /**
  * Application debug messages.
  */
  DEBUG : 'debug'
};
 
Logger.logPriority = [
  Logger.LogLevels.EMERGENCY,
  Logger.LogLevels.ALERT,
  Logger.LogLevels.CRITICAL,
  Logger.LogLevels.ERROR,
  Logger.LogLevels.WARNING,
  Logger.LogLevels.NOTICE,
  Logger.LogLevels.INFO,
  Logger.LogLevels.DEBUG
];
 
Logger.prototype.log = function (level, msg) {
  this.loggerFunction(level, msg);
};
 
Logger.prototype.emergency = function(msg) {
  this.log(Logger.LogLevels.EMERGENCY, msg);
};
 
Logger.prototype.critical = function(msg) {
  this.log(Logger.LogLevels.CRITICAL, msg);
};
 
Logger.prototype.alert = function(msg) {
  this.log(Logger.LogLevels.ALERT, msg);
};
 
Logger.prototype.error = function(msg) {
  this.log(Logger.LogLevels.ERROR, msg);
};
 
Logger.prototype.warn = function(msg) {
  this.log(Logger.LogLevels.WARNING, msg);
};
 
Logger.prototype.notice = function(msg) {
  this.log(Logger.LogLevels.NOTICE, msg);
};
 
Logger.prototype.info = function(msg) {
  this.log(Logger.LogLevels.INFO, msg);
};
 
Logger.prototype.debug = function(msg) {
  this.log(Logger.LogLevels.DEBUG, msg);
};
 
Logger.prototype.defaultLoggerFunction = function(logLevel , msg) {
  var currentLevelIndex = Logger.logPriority.indexOf(this.level);
  var logLevelIndex = Logger.logPriority.indexOf(logLevel);
  var time = new Date();
  var timeStamp = time.toISOString();
  if (logLevelIndex <= currentLevelIndex) {
    console.log('[' + timeStamp + ']' + this.level + ' : ' + msg);
  }
};
 
module.exports = Logger;
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/errors/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/errors/

Statements: 47.06% (16 / 34)      Branches: 0% (0 / 8)      Functions: 0% (0 / 5)      Lines: 47.06% (16 / 34)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/lib/common/errors/
File Statements Branches Functions Lines
errors.js 47.06% (16 / 34) 0% (0 / 8) 0% (0 / 5) 47.06% (16 / 34)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/errors/errors.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/errors/errors.js

Statements: 47.06% (16 / 34)      Branches: 0% (0 / 8)      Functions: 0% (0 / 5)      Lines: 47.06% (16 / 34)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69                                  1 1   1           1           1   1             1   1                   1   1           1   1 1 1 1 1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var util = require('util');
var _ = require('underscore');
 
function captureStackTrace(targetObject, constructorOpt) {
  if (Error.captureStackTrace) {
    Error.captureStackTrace(targetObject, constructorOpt);
  }
}
 
function ArgumentError(argumentName, message) {
  captureStackTrace(this, this.constructor); 
  this.name = this.constructor.name;
  this.argumentName = argumentName;
  this.message = message || util.format('Invalid or missing argument supplied: %s', argumentName);
}
util.inherits(ArgumentError, Error);
 
function ArgumentNullError(argumentName, message) {
  captureStackTrace(this, this.constructor); 
  this.name = this.constructor.name;
  this.argumentName = argumentName;
  this.message = message || util.format('Missing argument: %s', argumentName);
}
 
util.inherits(ArgumentNullError, Error);
 
function StorageError(message, properties) {
  captureStackTrace(this, this.constructor); 
  this.name = this.constructor.name;
  this.message = message;
  
  if(properties){
    _.extend(this, properties);
  }
}
 
util.inherits(StorageError, Error);
 
function TimeoutError(message) {
  captureStackTrace(this, this.constructor); 
  this.name = this.constructor.name;
  this.message = message;
}
 
util.inherits(TimeoutError, Error);
 
module.exports.ArgumentError = ArgumentError;
module.exports.ArgumentNullError = ArgumentNullError;
module.exports.StorageError = StorageError;
module.exports.TimeoutError = TimeoutError;
module.exports.captureStackTrace = captureStackTrace;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/filters/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/filters/

Statements: 24.77% (27 / 109)      Branches: 0% (0 / 105)      Functions: 0% (0 / 12)      Lines: 24.77% (27 / 109)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/lib/common/filters/
File Statements Branches Functions Lines
exponentialretrypolicyfilter.js 45% (9 / 20) 0% (0 / 12) 0% (0 / 3) 45% (9 / 20)
linearretrypolicyfilter.js 53.85% (7 / 13) 0% (0 / 8) 0% (0 / 3) 53.85% (7 / 13)
retrypolicyfilter.js 14.47% (11 / 76) 0% (0 / 85) 0% (0 / 6) 14.47% (11 / 76)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/filters/exponentialretrypolicyfilter.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/filters/exponentialretrypolicyfilter.js

Statements: 45% (9 / 20)      Branches: 0% (0 / 12)      Functions: 0% (0 / 3)      Lines: 45% (9 / 20)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97                                    1                                     1                   1         1         1         1                 1                                     1       1    
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
'use strict';
 
var RetryPolicyFilter = require('./retrypolicyfilter');
/**
* Creates a new 'ExponentialRetryPolicyFilter' instance.
* @class
* The ExponentialRetryPolicyFilter allows you to retry operations,
* using an exponential back-off interval between retries.
* To apply a filter to service operations, use `withFilter`
* and specify the filter to be used when creating a service.
* @constructor
* @param {number} [retryCount=3]            The client retry count.
* @param {number} [retryInterval=30000]     The client retry interval, in milliseconds.
* @param {number} [minRetryInterval=3000]   The minimum retry interval, in milliseconds.
* @param {number} [maxRetryInterval=90000]  The maximum retry interval, in milliseconds.
* 
* @example
* var azure = require('azure-storage');
* var retryOperations = new azure.ExponentialRetryPolicyFilter();
* var blobService = azure.createBlobService().withFilter(retryOperations)
*/
function ExponentialRetryPolicyFilter(retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
  this.retryCount = retryCount ? retryCount : ExponentialRetryPolicyFilter.DEFAULT_CLIENT_RETRY_COUNT;
  this.retryInterval = retryInterval ? retryInterval : ExponentialRetryPolicyFilter.DEFAULT_CLIENT_RETRY_INTERVAL;
  this.minRetryInterval = minRetryInterval ? minRetryInterval : ExponentialRetryPolicyFilter.DEFAULT_CLIENT_MIN_RETRY_INTERVAL;
  this.maxRetryInterval = maxRetryInterval ? maxRetryInterval : ExponentialRetryPolicyFilter.DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
}
 
/**
* Represents the default client retry interval, in milliseconds.
*/
ExponentialRetryPolicyFilter.DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30;
 
/**
* Represents the default client retry count.
*/
ExponentialRetryPolicyFilter.DEFAULT_CLIENT_RETRY_COUNT = 3;
 
/**
* Represents the default maximum retry interval, in milliseconds.
*/
ExponentialRetryPolicyFilter.DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90;
 
/**
* Represents the default minimum retry interval, in milliseconds.
*/
ExponentialRetryPolicyFilter.DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3;
 
/**
 * Determines if the operation should be retried and how long to wait until the next retry.
 *
 * @param {number} statusCode The HTTP status code.
 * @param {object} requestOptions  The request options.
 * @return {retryInfo} Information about whether the operation qualifies for a retry and the retryInterval.
 */
ExponentialRetryPolicyFilter.prototype.shouldRetry = function (statusCode, requestOptions) {
  var retryData = (requestOptions && requestOptions.retryContext) ? requestOptions.retryContext : {};
 
  // Adjust retry interval
  var incrementDelta = Math.pow(2, retryData.retryCount) - 1;
  var boundedRandDelta = this.retryInterval * 0.8 + Math.floor(Math.random() * (this.retryInterval * 1.2 - this.retryInterval * 0.8));
  incrementDelta *= boundedRandDelta;
      
  retryData.retryInterval = Math.min(this.minRetryInterval + incrementDelta, this.maxRetryInterval);
 
  return RetryPolicyFilter._shouldRetryOnError(statusCode, requestOptions);
};
 
/**
* Handles an operation with an exponential retry policy.
*
* @param {Object}   requestOptions The original request options.
* @param {function} next           The next filter to be handled.
*/
ExponentialRetryPolicyFilter.prototype.handle = function (requestOptions, next) {
  RetryPolicyFilter._handle(this, requestOptions, next);
};
 
module.exports = ExponentialRetryPolicyFilter;
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/filters/linearretrypolicyfilter.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/filters/linearretrypolicyfilter.js

Statements: 53.85% (7 / 13)      Branches: 0% (0 / 8)      Functions: 0% (0 / 3)      Lines: 53.85% (7 / 13)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77                                  1                                   1               1         1                 1                         1       1    
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
//
'use strict';
 
var RetryPolicyFilter = require('./retrypolicyfilter');
 
/**
* Creates a new LinearRetryPolicyFilter instance.
* @class
* The LinearRetryPolicyFilter allows you to retry operations,
* using an linear back-off interval between retries.
* To apply a filter to service operations, use `withFilter`
* and specify the filter to be used when creating a service.
* @constructor
* @param {number} [retryCount=3]            The client retry count.
* @param {number} [retryInterval=30000]     The client retry interval, in milliseconds.
*
* @example
* var azure = require('azure-storage');
* var retryOperations = new azure.LinearRetryPolicyFilter();
* var blobService = azure.createBlobService().withFilter(retryOperations)
*/
function LinearRetryPolicyFilter(retryCount, retryInterval) {
  this.retryCount = retryCount ? retryCount : LinearRetryPolicyFilter.DEFAULT_CLIENT_RETRY_COUNT;
  this.retryInterval = retryInterval ? retryInterval : LinearRetryPolicyFilter.DEFAULT_CLIENT_RETRY_INTERVAL;
}
 
/**
* Represents the default client retry interval, in milliseconds.
*/
LinearRetryPolicyFilter.DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30;
 
/**
* Represents the default client retry count.
*/
LinearRetryPolicyFilter.DEFAULT_CLIENT_RETRY_COUNT = 3;
 
/**
* Determines if the operation should be retried and how long to wait until the next retry.
*
 * @param {number} statusCode       The HTTP status code.
 * @param {object} requestOptions   The request options.
 * @return {retryInfo} Information about whether the operation qualifies for a retry and the retryInterval.
*/
LinearRetryPolicyFilter.prototype.shouldRetry = function (statusCode, requestOptions) {
  var retryData = (requestOptions && requestOptions.retryContext) ? requestOptions.retryContext : {};
  retryData.retryInterval = this.retryInterval;
 
  return RetryPolicyFilter._shouldRetryOnError(statusCode, requestOptions);
};
 
/**
* Handles an operation with a linear retry policy.
*
* @param {Object}   requestOptions The original request options.
* @param {function} next           The next filter to be handled.
*/
LinearRetryPolicyFilter.prototype.handle = function (requestOptions, next) {
  RetryPolicyFilter._handle(this, requestOptions, next);
};
 
module.exports = LinearRetryPolicyFilter;
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/filters/retrypolicyfilter.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/filters/retrypolicyfilter.js

Statements: 14.47% (11 / 76)      Branches: 0% (0 / 85)      Functions: 0% (0 / 6)      Lines: 14.47% (11 / 76)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235                                1 1 1 1                                               1               1         1               1                   1                                                                                                                                                                                                                                                     1                                                                     1    
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var azureutil = require('../util/util');
var Constants = require('../util/constants');
var StorageUtilities = require('../util/storageutilities');
var extend = require('util')._extend;
 
/**
* Creates a new RetryPolicyFilter instance.
* @class
* The RetryPolicyFilter allows you to retry operations,
* using a custom retry policy. Users are responsible to 
* define the shouldRetry method.
* To apply a filter to service operations, use `withFilter`
* and specify the filter to be used when creating a service.
* @constructor
* @param {number} [retryCount=30000]        The client retry count.
* @param {number} [retryInterval=3]     The client retry interval, in milliseconds.
*
* @example
* var azure = require('azure-storage');
* var retryPolicy = new azure.RetryPolicyFilter();
* retryPolicy.retryCount = 3;
* retryPolicy.retryInterval = 3000;
* retryPolicy.shouldRetry = function(statusCode, retryContext) {
*
* };
* var blobService = azure.createBlobService().withFilter(retryPolicy);
*/
function RetryPolicyFilter(retryCount, retryInterval) {
  this.retryCount = retryCount ? retryCount : RetryPolicyFilter.DEFAULT_CLIENT_RETRY_COUNT;
  this.retryInterval = retryInterval ? retryInterval : RetryPolicyFilter.DEFAULT_CLIENT_RETRY_INTERVAL;
}
 
/**
* Represents the default client retry interval, in milliseconds.
*/
RetryPolicyFilter.DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30;
 
/**
* Represents the default client retry count.
*/
RetryPolicyFilter.DEFAULT_CLIENT_RETRY_COUNT = 3;
 
/**
* Handles an operation with a retry policy.
*
* @param {Object}   requestOptions The original request options.
* @param {function} next           The next filter to be handled.
*/
RetryPolicyFilter.prototype.handle = function (requestOptions, next) {
  RetryPolicyFilter._handle(this, requestOptions, next);
};
 
/**
* Handles an operation with a retry policy.
*
* @param {Object}   requestOptions The original request options.
* @param {function} next           The next filter to be handled.
*/
RetryPolicyFilter._handle = function (self, requestOptions, next) {
 
  var retryRequestOptions = extend({}, requestOptions);
  retryRequestOptions.retryInterval = 0;
 
  // Initialize retryContext because that will be passed to the shouldRetry method which users will implement 
  retryRequestOptions.retryContext = {
    retryCount: 0,
    error: null,
    retryInterval: retryRequestOptions.retryInterval,
    locationMode: retryRequestOptions.locationMode,
    currentLocation: retryRequestOptions.currentLocation
  };
 
  var lastPrimaryAttempt;
  var lastSecondaryAttempt;
  var operation = function () {
    // retry policies dont really do anything to the request options
    // so move on to next
    if (next) {
      next(retryRequestOptions, function (returnObject, finalCallback, nextPostCallback) {
        // Previous operation ended so update the retry data
        if (returnObject.error) {
          if (retryRequestOptions.retryContext.error) {
            returnObject.error.innerError = retryRequestOptions.retryContext.error;
          }
 
          retryRequestOptions.retryContext.error = returnObject.error;
        }
 
        // If a request sent to the secondary location fails with 404 (Not Found), it is possible
        // that the resource replication is not finished yet. So, in case of 404 only in the secondary
        // location, the failure should still be retryable.
        var secondaryNotFound = (retryRequestOptions.currentLocation === Constants.StorageLocation.SECONDARY) && ((returnObject.response && returnObject.response.statusCode === 404) || (returnObject.error && returnObject.error.code === 'ENOTFOUND'));
 
        var notExceedMaxRetryCount = retryRequestOptions.retryContext.retryCount ? retryRequestOptions.retryContext.retryCount <= self.retryCount : true;
        var retryInfo = self.shouldRetry(secondaryNotFound ? 500 : (azureutil.objectIsNull(returnObject.response) ? 306 : returnObject.response.statusCode), retryRequestOptions);
        retryRequestOptions.retryContext.retryCount++;
 
        if (retryInfo.ignore) {
          returnObject.error = null;
        }
 
        // If the custom retry logic(shouldRetry) does not return a targetLocation, calculate based on the previous location and locationMode.
        if(azureutil.objectIsNull(retryInfo.targetLocation)) {
          retryInfo.targetLocation = azureutil.getNextLocation(retryRequestOptions.currentLocation, retryRequestOptions.locationMode);
        }
 
        // If the custom retry logic(shouldRetry) does not return a retryInterval, try to set it to the value on the instance if it is available. Otherwise, the default(30000) will be used.
        if(azureutil.objectIsNull(retryInfo.retryInterval)) {
          retryInfo.retryInterval = self.retryInterval;
        }
        
        // Only in the case of success from server but client side failure like MD5 or length mismatch, returnObject.retryable has a value(we explicitly set it to false). 
        // In this case, we should not retry the request.
        // If the output stream already get sent to server and get error back, 
        // we should NOT retry within the SDK as the stream data is not valid anymore if we retry directly.
        if (
            !returnObject.outputStreamSent && returnObject.error && azureutil.objectIsNull(returnObject.retryable) && notExceedMaxRetryCount &&
            (
              (!azureutil.objectIsNull(returnObject.response) && retryInfo.retryable) || 
              (
                returnObject.error.code === 'ECONNREFUSED' ||
                returnObject.error.code === 'ETIMEDOUT' ||
                returnObject.error.code === 'ESOCKETTIMEDOUT' || 
                returnObject.error.code === 'ECONNRESET' || 
                returnObject.error.code === 'EAI_AGAIN'
              )
            )
          ) {
          if (retryRequestOptions.currentLocation === Constants.StorageLocation.PRIMARY) {
            lastPrimaryAttempt = returnObject.operationEndTime;
          } else {
            lastSecondaryAttempt = returnObject.operationEndTime;
          }
 
          // Moreover, in case of 404 when trying the secondary location, instead of retrying on the
          // secondary, further requests should be sent only to the primary location, as it most
          // probably has a higher chance of succeeding there.
          if (secondaryNotFound && (retryRequestOptions.locationMode !== StorageUtilities.LocationMode.SECONDARY_ONLY))
          {
            retryInfo.locationMode = StorageUtilities.LocationMode.PRIMARY_ONLY;
            retryInfo.targetLocation = Constants.StorageLocation.PRIMARY;
          }
 
          // Now is the time to calculate the exact retry interval. ShouldRetry call above already
          // returned back how long two requests to the same location should be apart from each other.
          // However, for the reasons explained above, the time spent between the last attempt to
          // the target location and current time must be subtracted from the total retry interval
          // that ShouldRetry returned.
          var lastAttemptTime = retryInfo.targetLocation === Constants.StorageLocation.PRIMARY ? lastPrimaryAttempt : lastSecondaryAttempt;
          if (!azureutil.objectIsNull(lastAttemptTime)) {
            var sinceLastAttempt = new Date().getTime() - lastAttemptTime.getTime();
            if (sinceLastAttempt < 0) {
              sinceLastAttempt = 0;
            }
 
            retryRequestOptions.retryInterval = retryInfo.retryInterval - sinceLastAttempt;
          }
          else {
            retryRequestOptions.retryInterval = 0;
          }
 
          if(!azureutil.objectIsNull(retryInfo.locationMode)) {
            retryRequestOptions.locationMode = retryInfo.locationMode;
          }
 
          retryRequestOptions.currentLocation = retryInfo.targetLocation;
          operation();
        } else {
          if (nextPostCallback) {
            nextPostCallback(returnObject);
          } else if (finalCallback) {
            finalCallback(returnObject);
          }
        }
      });
    }
  };
 
  operation();
};
 
RetryPolicyFilter._shouldRetryOnError = function (statusCode, requestOptions) {
  var retryInfo = (requestOptions && requestOptions.retryContext) ? requestOptions.retryContext : {};
 
  // Non-timeout Cases
  if (statusCode >= 300 && statusCode != 408) {
    // Always no retry on "not implemented" and "version not supported"
    if (statusCode == 501 || statusCode == 505) {
      retryInfo.retryable = false;
      return retryInfo;
    }
    
    // When absorbConditionalErrorsOnRetry is set (for append blob)
    if (requestOptions && requestOptions.absorbConditionalErrorsOnRetry) {
      if (statusCode == 412) {
        // When appending block with precondition failure and their was a server error before, we ignore the error.
        if (retryInfo.lastServerError) {
          retryInfo.ignore = true;
          retryInfo.retryable = true;
        } else {
          retryInfo.retryable = false;
        }
      } else if (retryInfo.retryable && statusCode >= 500 && statusCode < 600) {
        // Retry on the server error
        retryInfo.retryable = true;
        retryInfo.lastServerError = true;
      }
    } else if (statusCode < 500) {
      // No retry on the client error
      retryInfo.retryable = false;
    }
  }
 
  return retryInfo;
};
 
module.exports = RetryPolicyFilter;
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/http/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/http/

Statements: 25.86% (30 / 116)      Branches: 0% (0 / 57)      Functions: 0% (0 / 22)      Lines: 25.86% (30 / 116)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/lib/common/http/
File Statements Branches Functions Lines
webresource.js 25.86% (30 / 116) 0% (0 / 57) 0% (0 / 22) 25.86% (30 / 116)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/http/webresource.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/http/webresource.js

Statements: 25.86% (30 / 116)      Branches: 0% (0 / 57)      Functions: 0% (0 / 22)      Lines: 25.86% (30 / 116)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325                                  1 1 1 1 1 1 1 1 1   1                       1                     1                         1                         1                         1                         1                         1                           1                               1                   1                                   1                                   1                                     1                                       1                         1                       1                                                                         1               1                             1               1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var azureutil = require('../util/util');
var SR = require('../util/sr');
var Constants = require('../util/constants');
var errors = require('../errors/errors');
var ArgumentError = errors.ArgumentError;
var HeaderConstants = Constants.HeaderConstants;
var HttpConstants = Constants.HttpConstants;
var HttpConstants = Constants.HttpConstants;
var HttpVerbs = HttpConstants.HttpVerbs;
 
function encodeSpecialCharacters(path) {
  return path.replace(/'/g, '%27');
}
 
/**
* Creates a new WebResource object.
*
* This class provides an abstraction over a REST call by being library / implementation agnostic and wrapping the necessary
* properties to initiate a request.
*
* @constructor
*/
function WebResource() {
  this.rawResponse = false;
  this.queryString = {};
}
 
/**
* Creates a new put request web resource.
*
* @param {string} path The path for the put operation.
* @return {WebResource} A new webresource with a put operation for the given path.
*/
WebResource.put = function (path) {
  var webResource = new WebResource();
  webResource.path = path ? encodeSpecialCharacters(path) : null;
  webResource.method = HttpConstants.HttpVerbs.PUT;
  return webResource;
};
 
/**
* Creates a new get request web resource.
*
* @param {string} path The path for the get operation.
* @return {WebResource} A new webresource with a get operation for the given path.
*/
WebResource.get = function (path) {
  var webResource = new WebResource();
  webResource.path = path ? encodeSpecialCharacters(path) : null;
  webResource.method = HttpConstants.HttpVerbs.GET;
  return webResource;
};
 
/**
* Creates a new head request web resource.
*
* @param {string} path The path for the head operation.
* @return {WebResource} A new webresource with a head operation for the given path.
*/
WebResource.head = function (path) {
  var webResource = new WebResource();
  webResource.path = path ? encodeSpecialCharacters(path) : null;
  webResource.method = HttpConstants.HttpVerbs.HEAD;
  return webResource;
};
 
/**
* Creates a new delete request web resource.
*
* @param {string} path The path for the delete operation.
* @return {WebResource} A new webresource with a delete operation for the given path.
*/
WebResource.del = function (path) {
  var webResource = new WebResource();
  webResource.path = path ? encodeSpecialCharacters(path) : null;
  webResource.method = HttpConstants.HttpVerbs.DELETE;
  return webResource;
};
 
/**
* Creates a new post request web resource.
*
* @param {string} path The path for the post operation.
* @return {WebResource} A new webresource with a post operation for the given path.
*/
WebResource.post = function (path) {
  var webResource = new WebResource();
  webResource.path = path ? encodeSpecialCharacters(path) : null;
  webResource.method = HttpConstants.HttpVerbs.POST;
  return webResource;
};
 
/**
* Creates a new merge request web resource.
*
* @param {string} path The path for the merge operation.
* @return {WebResource} A new webresource with a merge operation for the given path.
*/
WebResource.merge = function (path) {
  var webResource = new WebResource();
  webResource.path = path ? encodeSpecialCharacters(path) : null;
  webResource.method = HttpConstants.HttpVerbs.MERGE;
  return webResource;
};
 
/**
* Specifies a custom property in the web resource.
*
* @param {string} name  The property name.
* @param {string} value The property value.
* @return {WebResource} The webresource.
*/
WebResource.prototype.withProperty = function (name, value) {
  if (!this.properties) {
    this.properties = {};
  }
 
  this.properties[name] = value;
 
  return this;
};
 
/**
* Specifies if the response should be parsed or not.
*
* @param {bool} rawResponse true if the response should not be parsed; false otherwise.
* @return {WebResource} The webresource.
*/
WebResource.prototype.withRawResponse = function (rawResponse) {
  this.rawResponse = rawResponse;
 
  if (azureutil.objectIsNull(this.rawResponse)) {
    this.rawResponse = true;
  }
 
  return this;
};
 
WebResource.prototype.withHeadersOnly = function (headersOnly) {
  if (headersOnly !== undefined) {
    this.headersOnly = headersOnly;
  } else {
    this.headersOnly = true;
  }
 
  return this;
};
 
/**
* Adds an optional query string parameter.
*
* @param {Object} name          The name of the query string parameter.
* @param {Object} value         The value of the query string parameter.
* @param {Object} defaultValue  The default value for the query string parameter to be used if no value is passed.
* @return {Object} The web resource.
*/
WebResource.prototype.withQueryOption = function (name, value, defaultValue) {
  if (!azureutil.objectIsNull(value)) {
    this.queryString[name] = value;
  } else if (defaultValue) {
    this.queryString[name] = defaultValue;
  }
 
  return this;
};
 
/**
* Adds optional query string parameters.
*
* Additional arguments will be the needles to search in the haystack. 
*
* @param {Object} object  The haystack of query string parameters.
* @return {Object} The web resource.
*/
WebResource.prototype.withQueryOptions = function (object) {
  if (object) {
    for (var i = 1; i < arguments.length; i++) {
      if (object[arguments[i]]) {
        this.withQueryOption(arguments[i], object[arguments[i]]);
      }
    }
  }
 
  return this;
};
 
/**
* Adds an optional header parameter.
*
* @param {Object} name  The name of the header parameter.
* @param {Object} value The value of the header parameter.
* @return {Object} The web resource.
*/
WebResource.prototype.withHeader = function (name, value) {
  if (!this.headers) {
    this.headers = {};
  }
 
  if (!azureutil.IsNullOrEmptyOrUndefinedOrWhiteSpace(value)) {
    value = value instanceof Date ? value.toUTCString() : value;
    
    this.headers[name] = value;
  }
 
  return this;
};
 
/**
* Adds an optional body.
*
* @param {Object} body  The request body.
* @return {Object} The web resource.
*/
WebResource.prototype.withBody = function (body) {
  this.body = body;
  return this;
};
 
/**
* Adds optional query string parameters.
*
* Additional arguments will be the needles to search in the haystack. 
*
* @param {Object} object  The haystack of headers.
* @return {Object} The web resource.
*/
WebResource.prototype.withHeaders = function (object) {
  if (object) {
    for (var i = 1; i < arguments.length; i++) {
      if (object[arguments[i]]) {
        this.withHeader(arguments[i], object[arguments[i]]);
      }
    }
  }
 
  return this;
};
 
WebResource.prototype.addOptionalMetadataHeaders = function (metadata) {
  var self = this;
 
  if (metadata) {
    Object.keys(metadata).forEach(function (metadataKey) {
      if (azureutil.IsNullOrEmptyOrUndefinedOrWhiteSpace(metadataKey)) {
        throw new ArgumentError('metadata', SR.METADATA_KEY_INVALID);
      }
 
      var value = metadata[metadataKey];
      if (azureutil.IsNullOrEmptyOrUndefinedOrWhiteSpace(value)) {
        throw new ArgumentError('metadata', SR.METADATA_VALUE_INVALID);
      }
      
      var metadataHeaderName = HeaderConstants.PREFIX_FOR_STORAGE_METADATA + metadataKey;
      var existingMetadataHeaderName = '';
      var headers = self.headers ? self.headers : {};
      if (Object.keys(headers).some(function (headerName) {
        existingMetadataHeaderName = headerName;
        return headerName.toString().toLowerCase() === metadataHeaderName.toLowerCase();
      })) {        
        self.withHeader(existingMetadataHeaderName, self.headers[existingMetadataHeaderName] + ',' + value);
      } else {
        self.withHeader(metadataHeaderName, value);
      }
    });
  }
 
  return this;
};
 
/**
* Determines if a status code corresponds to a valid response according to the WebResource's expected status codes.
*
* @param {int} statusCode The response status code.
* @return true if the response is valid; false otherwise.
*/
WebResource.validResponse = function (statusCode) {
  if (statusCode >= 200 && statusCode < 300) {
    return true;
  }
 
  return false;
};
 
function isMethodWithBody(verb) {
  return verb === HttpVerbs.PUT ||
    verb === HttpVerbs.POST ||
    verb === HttpVerbs.MERGE;
}
 
/**
* Hook up the given input stream to a destination output stream if the WebResource method
* requires a request body and a body is not already set.
*
* @param {Stream} inputStream the stream to pipe from
* @param {Stream} outputStream the stream to pipe to
*
* @return destStream
*/
WebResource.prototype.pipeInput = function(inputStream, destStream) {
  if (isMethodWithBody(this.method) && !this.hasOwnProperty('body')) {
    inputStream.pipe(destStream);
  }
 
  return destStream;
};
 
module.exports = WebResource;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/md5-wrapper/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/md5-wrapper/

Statements: 80% (4 / 5)      Branches: 100% (0 / 0)      Functions: 0% (0 / 2)      Lines: 80% (4 / 5)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/lib/common/md5-wrapper/
File Statements Branches Functions Lines
node.js 80% (4 / 5) 100% (0 / 0) 0% (0 / 2) 80% (4 / 5)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/md5-wrapper/node.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/md5-wrapper/node.js

Statements: 80% (4 / 5)      Branches: 100% (0 / 0)      Functions: 0% (0 / 2)      Lines: 80% (4 / 5)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27                                1   1     1       1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var crypto = require('crypto');
 
var Md5Wrapper = function () {
};
 
Md5Wrapper.prototype.createMd5Hash = function() {
    return crypto.createHash('md5');
};
 
module.exports = Md5Wrapper;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/models/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/models/

Statements: 11.98% (26 / 217)      Branches: 0% (0 / 147)      Functions: 0% (0 / 17)      Lines: 11.98% (26 / 217)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/lib/common/models/
File Statements Branches Functions Lines
aclresult.js 18.75% (9 / 48) 0% (0 / 24) 0% (0 / 4) 18.75% (9 / 48)
servicepropertiesresult.js 9.43% (15 / 159) 0% (0 / 115) 0% (0 / 12) 9.43% (15 / 159)
servicestatsparser.js 20% (2 / 10) 0% (0 / 8) 0% (0 / 1) 20% (2 / 10)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/models/aclresult.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/models/aclresult.js

Statements: 18.75% (9 / 48)      Branches: 0% (0 / 24)      Functions: 0% (0 / 4)      Lines: 18.75% (9 / 48)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123                                  1 1   1 1 1 1   1               1                                                                                                                   1                                                              
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var _ = require('underscore');
var xmlbuilder = require('xmlbuilder');
 
var azureutil = require('../util/util');
var ISO8061Date = require('../util/iso8061date');
var Constants = require('../util/constants');
var AclConstants = Constants.AclConstants;
 
exports = module.exports;
 
/**
* Builds an XML representation for container acl permissions.
*
* @param  {Object.<string, AccessPolicy>}  entity The signed identifiers.
* @return {string} The XML container acl permissions.
*/
exports.serialize = function (signedIdentifiersJs) {
  var doc = xmlbuilder.create();
  doc = doc.begin(AclConstants.SIGNED_IDENTIFIERS_ELEMENT, { version: '1.0', encoding: 'utf-8' });
 
  var keys = Object.keys(signedIdentifiersJs);
  if (keys.length > 0) {
    keys.forEach(function (key) {
      var accessPolicy = signedIdentifiersJs[key];
      doc = doc
        .ele(AclConstants.SIGNED_IDENTIFIER_ELEMENT)
          .ele(AclConstants.ID)
            .txt(key)
          .up()
          .ele(AclConstants.ACCESS_POLICY);
 
      if (accessPolicy.Start) {
        var startIsoString = accessPolicy.Start;
        if (!_.isDate(startIsoString)) {
          startIsoString = new Date(startIsoString);
        }
 
        // Convert to expected ISO 8061 date format
        startIsoString = ISO8061Date.format(startIsoString);
 
        doc = doc
            .ele(AclConstants.START)
              .txt(startIsoString)
            .up();
      }
 
      if (accessPolicy.Expiry) {
        var expiryIsoString = accessPolicy.Expiry;
        if (!_.isDate(expiryIsoString)) {
          expiryIsoString = new Date(expiryIsoString);
        }
 
        // Convert to expected ISO 8061 date format
        expiryIsoString = ISO8061Date.format(expiryIsoString);
 
        doc = doc
            .ele(AclConstants.EXPIRY)
              .txt(expiryIsoString)
            .up();
      }
 
      if (accessPolicy.Permissions) {
        doc = doc
            .ele(AclConstants.PERMISSION)
              .txt(accessPolicy.Permissions)
            .up();
      }
 
      doc = doc.up().up();
    });
  }
  return doc.doc().toString();
};
 
exports.parse = function (signedIdentifiersXml) {
  var signedIdentifiers = {};
 
  signedIdentifiersXml = azureutil.tryGetValueChain(signedIdentifiersXml, [ 'SignedIdentifiers', 'SignedIdentifier' ]);
  if (signedIdentifiersXml) {
    if (!_.isArray(signedIdentifiersXml)) {
      signedIdentifiersXml = [ signedIdentifiersXml ];
    }
 
    signedIdentifiersXml.forEach(function (signedIdentifier) {
      var accessPolicy = {};
      if (signedIdentifier.AccessPolicy) {
        if (signedIdentifier.AccessPolicy.Start) {
          accessPolicy.Start = ISO8061Date.parse(signedIdentifier.AccessPolicy.Start);
        }
 
        if (signedIdentifier.AccessPolicy.Expiry) {
          accessPolicy.Expiry = ISO8061Date.parse(signedIdentifier.AccessPolicy.Expiry);
        }
 
        if (signedIdentifier.AccessPolicy.Permission) {
          accessPolicy.Permissions = signedIdentifier.AccessPolicy.Permission;
        }
      }
 
      signedIdentifiers[signedIdentifier.Id] = accessPolicy;
    });
  }
 
  return signedIdentifiers;
};
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/models/servicepropertiesresult.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/models/servicepropertiesresult.js

Statements: 9.43% (15 / 159)      Branches: 0% (0 / 115)      Functions: 0% (0 / 12)      Lines: 9.43% (15 / 159)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374                                  1 1   1 1   1   1                                                             1                                                                                           1                                                                     1                                                                                                       1                                                                         1                           1                                                   1                                           1                                                                                                                       1                                                  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var _ = require('underscore');
var xmlbuilder = require('xmlbuilder');
 
var Constants = require('../util/constants');
var ServicePropertiesConstants = Constants.ServicePropertiesConstants;
 
exports = module.exports;
 
function serializeRetentionPolicy(doc, policy){
  if(policy !== null){
    if (typeof policy === 'undefined'){
      policy = {};
    }
 
    doc = doc.ele(ServicePropertiesConstants.RETENTION_POLICY_ELEMENT);
    if (typeof policy.Enabled !== 'undefined') {
      doc = doc.ele(ServicePropertiesConstants.ENABLED_ELEMENT)
                .txt(policy.Enabled)
               .up();
    } else {
      doc = doc.ele(ServicePropertiesConstants.ENABLED_ELEMENT)
                .txt(false)
                .up();
    }
 
    if (typeof policy.Days !== 'undefined') {
      doc = doc.ele(ServicePropertiesConstants.DAYS_ELEMENT)
                .txt(policy.Days)
               .up();
    } else if (policy.Enabled === true){
      doc = doc.ele(ServicePropertiesConstants.DAYS_ELEMENT)
                .txt(1)
                .up();
    }
 
    doc = doc.up();
  }
}
 
function serializeLogging(doc, logging){
  if (typeof logging.Version !== 'undefined') {
    doc = doc.ele(ServicePropertiesConstants.VERSION_ELEMENT)
            .txt(logging.Version)
          .up();
  } else {
    doc = doc.ele(ServicePropertiesConstants.VERSION_ELEMENT)
        .txt(ServicePropertiesConstants.DEFAULT_ANALYTICS_VERSION)
      .up();
  }
 
  if (typeof logging.Delete !== 'undefined') {
    doc = doc.ele(ServicePropertiesConstants.DELETE_ELEMENT)
            .txt(logging.Delete)
          .up();
  } else {
    doc = doc.ele(ServicePropertiesConstants.DELETE_ELEMENT)
        .txt(false)
      .up();
  }
 
  if (typeof logging.Read !== 'undefined') {
    doc = doc.ele(ServicePropertiesConstants.READ_ELEMENT)
            .txt(logging.Read)
          .up();
  } else {
    doc = doc.ele(ServicePropertiesConstants.READ_ELEMENT)
        .txt(false)
      .up();
  }
 
  if (typeof logging.Write !== 'undefined') {
    doc = doc.ele(ServicePropertiesConstants.WRITE_ELEMENT)
            .txt(logging.Write)
          .up();
  } else {
    doc = doc.ele(ServicePropertiesConstants.WRITE_ELEMENT)
        .txt(false)
      .up();
  }
 
  serializeRetentionPolicy(doc, logging.RetentionPolicy);
 
  doc = doc.up();
}
 
function serializeMetrics(doc, metrics){
  if (typeof metrics.Version !== 'undefined') {
    doc = doc.ele(ServicePropertiesConstants.VERSION_ELEMENT)
            .txt(metrics.Version)
          .up();
  } else {
    doc = doc.ele(ServicePropertiesConstants.VERSION_ELEMENT)
        .txt(ServicePropertiesConstants.DEFAULT_ANALYTICS_VERSION)
      .up();
  }
 
  if (typeof metrics.Enabled !== 'undefined') {
    doc = doc.ele(ServicePropertiesConstants.ENABLED_ELEMENT)
            .txt(metrics.Enabled)
          .up();
  } else {
    doc = doc.ele(ServicePropertiesConstants.ENABLED_ELEMENT)
        .txt(false)
      .up();
  }
 
  if(metrics.Enabled) {
    if (typeof metrics.IncludeAPIs !== 'undefined') {
      doc = doc.ele(ServicePropertiesConstants.INCLUDE_APIS_ELEMENT)
              .txt(metrics.IncludeAPIs)
            .up();
    } else if (metrics.Enabled === true){
      doc = doc.ele(ServicePropertiesConstants.INCLUDE_APIS_ELEMENT)
          .txt(false)
        .up();
    }
  }
  serializeRetentionPolicy(doc, metrics.RetentionPolicy);
}
 
function serializeCorsRules(doc, rules){
  if(typeof rules !== 'undefined' && rules !== null && _.isArray(rules)){
    rules.forEach(function (rule) {
      doc = doc.ele(ServicePropertiesConstants.CORS_RULE_ELEMENT);
      
      if(typeof rule.AllowedMethods !== 'undefined' && _.isArray(rule.AllowedMethods)){
        doc = doc.ele(ServicePropertiesConstants.ALLOWED_METHODS_ELEMENT)
                .txt(rule.AllowedMethods.join(','))
                .up();
      }
 
      if(typeof rule.AllowedOrigins !== 'undefined' && _.isArray(rule.AllowedOrigins)){
        doc = doc.ele(ServicePropertiesConstants.ALLOWED_ORIGINS_ELEMENT)
                .txt(rule.AllowedOrigins.join(','))
                .up();
      }
 
      if(typeof rule.AllowedHeaders !== 'undefined' && _.isArray(rule.AllowedHeaders)){
        doc = doc.ele(ServicePropertiesConstants.ALLOWED_HEADERS_ELEMENT)
                .txt(rule.AllowedHeaders.join(','))
                .up();
      } else {
        doc = doc.ele(ServicePropertiesConstants.ALLOWED_HEADERS_ELEMENT)
                .txt('')
                .up();
      }
 
      if(typeof rule.ExposedHeaders !== 'undefined' && _.isArray(rule.ExposedHeaders)){
        doc = doc.ele(ServicePropertiesConstants.EXPOSED_HEADERS_ELEMENT)
                .txt(rule.ExposedHeaders.join(','))
                .up();
      } else {
        doc = doc.ele(ServicePropertiesConstants.EXPOSED_HEADERS_ELEMENT)
                .txt('')
                .up();
      }
 
      if(typeof rule.MaxAgeInSeconds !== 'undefined'){
        doc = doc.ele(ServicePropertiesConstants.MAX_AGE_IN_SECONDS_ELEMENT)
                .txt(rule.MaxAgeInSeconds)
                .up();
      } else {
        doc = doc.ele(ServicePropertiesConstants.MAX_AGE_IN_SECONDS_ELEMENT)
                .txt('0')
                .up();
      }
 
      doc = doc.up();
    });
  }
}
 
exports.serialize = function (servicePropertiesJs) {
  var doc = xmlbuilder.create();
  doc = doc.begin(ServicePropertiesConstants.STORAGE_SERVICE_PROPERTIES_ELEMENT, { version: '1.0', encoding: 'utf-8' });
 
  if (servicePropertiesJs.Logging) {
    doc = doc.ele(ServicePropertiesConstants.LOGGING_ELEMENT);
    serializeLogging(doc, servicePropertiesJs.Logging);
    doc = doc.up();
  }
 
  if (servicePropertiesJs.HourMetrics) {
    doc = doc.ele(ServicePropertiesConstants.HOUR_METRICS_ELEMENT);
    serializeMetrics(doc, servicePropertiesJs.HourMetrics);
    doc = doc.up();
  }
 
  if (servicePropertiesJs.MinuteMetrics) {
    doc = doc.ele(ServicePropertiesConstants.MINUTE_METRICS_ELEMENT);
    serializeMetrics(doc, servicePropertiesJs.MinuteMetrics);
    doc = doc.up();
  }
 
  if (servicePropertiesJs.Cors) {
    doc = doc.ele(ServicePropertiesConstants.CORS_ELEMENT);
    serializeCorsRules(doc, servicePropertiesJs.Cors.CorsRule);
    doc = doc.up();
  }
 
  if (servicePropertiesJs.DefaultServiceVersion) {
    doc = doc.ele(ServicePropertiesConstants.DEFAULT_SERVICE_VERSION_ELEMENT)
               .txt(servicePropertiesJs.DefaultServiceVersion)
             .up();
  }
 
  return doc.doc().toString();
};
 
function parseRetentionPolicy(policyXml){
    var policy = {};
 
    if (typeof policyXml.Enabled !== 'undefined') {
      policy.Enabled = policyXml.Enabled === 'true';
    }
 
    if (typeof policyXml.Days !== 'undefined') {
      policy.Days = parseInt(policyXml.Days, 10);
    }
 
    return policy;
}
 
function parseLogging(loggingXml){
  var logging = {};
 
  if (typeof loggingXml.Version !== 'undefined') {
    logging.Version = loggingXml.Version;
  }
 
  if (typeof loggingXml.Delete !== 'undefined') {
    logging.Delete = loggingXml.Delete === 'true';
  }
 
  if (typeof loggingXml.Read !== 'undefined') {
    logging.Read = loggingXml.Read === 'true';
  }
 
  if (typeof loggingXml.Write !== 'undefined') {
    logging.Write = loggingXml.Write === 'true';
  }
 
  if (typeof loggingXml.RetentionPolicy !== 'undefined') {
    logging.RetentionPolicy = parseRetentionPolicy(loggingXml.RetentionPolicy);
  }
 
  return logging;
}
 
function parseMetrics(metricsXml){
  var metrics = {};
 
  if (typeof metricsXml.Version !== 'undefined') {
    metrics.Version = metricsXml.Version;
  }
 
  if (typeof metricsXml.Enabled !== 'undefined') {
    metrics.Enabled = metricsXml.Enabled === 'true';
  }
 
  if (typeof metricsXml.IncludeAPIs !== 'undefined') {
    metrics.IncludeAPIs = metricsXml.IncludeAPIs === 'true';
  }
 
  if (typeof metricsXml.RetentionPolicy !== 'undefined') {
    metrics.RetentionPolicy = parseRetentionPolicy(metricsXml.RetentionPolicy);
  }
 
  return metrics;
}
 
function parseCors(corsXml){
  var cors = {};
 
  if (typeof corsXml.CorsRule !== 'undefined') {
    var rulesXml = corsXml.CorsRule;
    if (!_.isArray(rulesXml)) {
        rulesXml = [ rulesXml ];
    }
 
    cors.CorsRule = [];
    rulesXml.forEach(function (ruleXml) {
      var rule = {};
 
      if(typeof ruleXml.AllowedMethods !== 'undefined'){
        if(ruleXml.AllowedMethods  !== ''){
          rule.AllowedMethods = ruleXml.AllowedMethods.split(',');
        }
        else {
          rule.AllowedMethods = [];
        }
      }
 
      if(typeof ruleXml.AllowedOrigins !== 'undefined'){
        if(ruleXml.AllowedOrigins  !== ''){
          rule.AllowedOrigins = ruleXml.AllowedOrigins.split(',');
        }
        else {
          rule.AllowedOrigins = [];
        }
      }
 
      if(typeof ruleXml.AllowedHeaders !== 'undefined'){
        if(ruleXml.AllowedHeaders  !== ''){
          rule.AllowedHeaders = ruleXml.AllowedHeaders.split(',');
        }
        else {
          rule.AllowedHeaders = [];
        }
      }
 
      if(typeof ruleXml.ExposedHeaders !== 'undefined'){
        if(ruleXml.ExposedHeaders  !== ''){
          rule.ExposedHeaders = ruleXml.ExposedHeaders.split(',');
        }
        else {
          rule.ExposedHeaders = [];
        }
      }
 
      if(typeof ruleXml.MaxAgeInSeconds !== 'undefined'){
        rule.MaxAgeInSeconds = parseInt(ruleXml.MaxAgeInSeconds, 10);
      }
 
      cors.CorsRule.push(rule);
    });
  }
 
  return cors;
}
 
exports.parse = function (servicePropertiesXml) {
  var serviceProperties = {};
 
  if (typeof servicePropertiesXml.Logging !== 'undefined') {
    serviceProperties.Logging = parseLogging(servicePropertiesXml.Logging); 
  }
 
  if (typeof servicePropertiesXml.HourMetrics !== 'undefined') {
    serviceProperties.HourMetrics = parseMetrics(servicePropertiesXml.HourMetrics);
  }
 
  if (typeof servicePropertiesXml.MinuteMetrics !== 'undefined') {
    serviceProperties.MinuteMetrics = parseMetrics(servicePropertiesXml.MinuteMetrics);
  }
 
  if (typeof servicePropertiesXml.Cors !== 'undefined') {
    serviceProperties.Cors = parseCors(servicePropertiesXml.Cors);
  }
 
  if (typeof servicePropertiesXml.DefaultServiceVersion !== 'undefined') {
    serviceProperties.DefaultServiceVersion = servicePropertiesXml.DefaultServiceVersion;
  }
 
  return serviceProperties;
};
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/models/servicestatsparser.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/models/servicestatsparser.js

Statements: 20% (2 / 10)      Branches: 0% (0 / 8)      Functions: 0% (0 / 1)      Lines: 20% (2 / 10)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35                              1   1                                  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
exports = module.exports;
 
exports.parse = function (serviceStatsXml) {
  var serviceStats = {};
 
  if (typeof serviceStatsXml.GeoReplication !== 'undefined') {   
    serviceStats.GeoReplication = {};
 
    if (typeof serviceStatsXml.GeoReplication.Status !== 'undefined') {
      serviceStats.GeoReplication.Status = serviceStatsXml.GeoReplication.Status;
    }
 
    if (typeof serviceStatsXml.GeoReplication.LastSyncTime !== 'undefined' && serviceStatsXml.GeoReplication.LastSyncTime !== '') {
      serviceStats.GeoReplication.LastSyncTime = new Date(serviceStatsXml.GeoReplication.LastSyncTime);
    }
  }
 
  return serviceStats;
};
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/services/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/services/

Statements: 16.69% (128 / 767)      Branches: 0% (0 / 426)      Functions: 2% (2 / 100)      Lines: 16.78% (128 / 763)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/lib/common/services/
File Statements Branches Functions Lines
servicesettings.js 30.77% (28 / 91) 0% (0 / 36) 15.38% (2 / 13) 30.77% (28 / 91)
storageserviceclient.js 12.5% (69 / 552) 0% (0 / 327) 0% (0 / 78) 12.59% (69 / 548)
storageservicesettings.js 25% (31 / 124) 0% (0 / 63) 0% (0 / 9) 25% (31 / 124)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/services/servicesettings.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/services/servicesettings.js

Statements: 30.77% (28 / 91)      Branches: 0% (0 / 36)      Functions: 15.38% (2 / 13)      Lines: 30.77% (28 / 91)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263                                1   1 1 1 1   1         1   1         1 1   1                 1                     1                       1                                                                                               1                                                                                                 1 3   3                                     3               1                   1                   1                       1 11 11 11   11                     1                                  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var util = require('util');
 
var azureUtil = require('../util/util');
var errors = require('../errors/errors');
var SR = require('../util/sr');
var Constants = require('../util/constants');
 
exports = module.exports;
 
/**
* The default protocol.
*/
exports.DEFAULT_PROTOCOL = Constants.HTTPS;
 
var NoMatchError = function (msg, constr) {
  errors.captureStackTrace(this, constr || this);
  this.message = msg || 'Error';
};
 
util.inherits(NoMatchError, Error);
NoMatchError.prototype.name = 'NoMatchError';
 
exports.NoMatchError = NoMatchError;
 
/**
* Throws an exception if the connection string format does not match any of the
* available formats.
*
* @param {string} connectionString The invalid formatted connection string.
* @return none
*/
exports.noMatchConnectionString = function (connectionString) {
  throw new NoMatchError('The provided connection string "' + connectionString + '" does not have complete configuration settings.');
};
 
/**
* Throws an exception if the settings dont match any of the
* available formats.
*
* @param {object} settings The invalid settings.
* @return none
*/
exports.noMatchSettings = function (settings) {
  throw new NoMatchError('The provided settings ' + JSON.stringify(settings) + ' are not complete.');
};
 
/**
* Parses the connection string and then validate that the parsed keys belong to
* the validSettingKeys
*
* @param {string} connectionString The user provided connection string.
* @param {array}  validKeys        The valid keys.
* @return {array} The tokenized connection string keys.
*/
exports.parseAndValidateKeys = function (connectionString, validKeys) {
  var parsedConnectionString = { };
 
  // parse key/value pairs from connection string
  var pairs = connectionString.split(';');
  for (var m = 0; m < pairs.length; m++) {
    if (pairs[m].length === 0) {
        continue;
    }
 
    var equalDex = pairs[m].indexOf('=');
    if (equalDex < 0) {
        throw new SyntaxError(SR.INVALID_CONNECTION_STRING);
    } else if (equalDex === 0) {
      // empty key name.
      throw new SyntaxError(SR.INVALID_CONNECTION_STRING_EMPTY_KEY);
    }
 
    var key = pairs[m].substring(0, equalDex);
 
    // assure that all given keys are valid.
    if (!azureUtil.inArrayInsensitive(key, validKeys)) {
      throw new SyntaxError(util.format(SR.INVALID_CONNECTION_STRING_BAD_KEY, key));
    }
 
    var value = pairs[m].substring(equalDex + 1);
    
    if(typeof parsedConnectionString[key] === 'undefined'){
      parsedConnectionString[key] = value;
    } else {
      // duplicate key name
      throw new SyntaxError(util.format(SR.INVALID_CONNECTION_STRING_DUPLICATE_KEY, key));
    }
  }
 
  return parsedConnectionString;
};
 
/**
* Creates an anonymous function that acts as predicate to perform a validation.
*
* @param array   {requirements} The array of conditions to satisfy.
* @param boolean {isRequired}   Either these conditions are all required or all
* optional.
* @param boolean {atLeastOne}   Indicates that at least one requirement must
* succeed.
* @return {function}
*/
exports.getValidator = function (requirements, isRequired, atLeastOne) {
  return function (userSettings) {
    var oneFound = false;
    var result = { };
 
    for (var key in userSettings) {
      if (userSettings.hasOwnProperty(key)) {
        result[key.toLowerCase()] = userSettings[key];
      }
    }
 
    for (var requirement in requirements) {
      if (requirements.hasOwnProperty(requirement)) {
        var settingName = requirements[requirement].SettingName.toLowerCase();
 
        // Check if the setting name exists in the provided user settings.
        if (result[settingName]) {
          // Check if the provided user setting value is valid.
          var validationFunc = requirements[requirement].SettingConstraint;
          var isValid = validationFunc(result[settingName]);
 
          if (isValid) {
            // Remove the setting as indicator for successful validation.
            delete result[settingName];
            oneFound = true;
          }
        } else if (isRequired) {
          // If required then fail because the setting does not exist
          return null;
        }
      }
    }
 
    if (atLeastOne) {
      // At least one requirement must succeed, otherwise fail.
      return oneFound ? result : null;
    } else {
      return result;
    }
  };
};
 
/**
* Creates a setting value condition that validates it is one of the
* passed valid values.
*
* @param {string} name The setting key name.
* @return {array}
*/
exports.setting = function (name) {
  var validValues = Array.prototype.slice.call(arguments, 1, arguments.length);
 
  var predicate = function (settingValue) {
    var validValuesString = JSON.stringify(validValues);
    if (validValues.length === 0) {
      // No restrictions, succeed.
      return true;
    }
 
    // Check to find if the settingValue is valid or not.
    for (var index = 0; index < validValues.length; index++) {
      if (settingValue.toString() == validValues[index].toString()) {
        // SettingValue is found in valid values set, succeed.
        return true;
      }
    }
 
    // settingValue is missing in valid values set, fail.
    throw new RangeError('The provided config value ' + settingValue + ' does not belong to the valid values subset:\n' + validValuesString);
  };
 
  return exports.settingWithFunc(name, predicate);
};
 
/**
* Creates an "at lease one" predicate for the provided list of requirements.
*
* @return callable
*/
exports.atLeastOne = function () {
  var allSettings = arguments;
  return exports.getValidator(allSettings, false, true);
};
 
/**
* Creates an optional predicate for the provided list of requirements.
*
* @return {function}
*/
exports.optional = function () {
  var optionalSettings = arguments;
  return exports.getValidator(optionalSettings, false, false);
};
 
/**
* Creates an required predicate for the provided list of requirements.
*
* @return {function}
*/
exports.allRequired = function () {
  var requiredSettings = arguments;
  return exports.getValidator(requiredSettings, true, false);
};
 
/**
* Creates a setting value condition using the passed predicate.
*
* @param {string}   name      The setting key name.
* @param {function} predicate The setting value predicate.
* @return {array}
*/
exports.settingWithFunc = function (name, predicate) {
  var requirement = {};
  requirement.SettingName = name;
  requirement.SettingConstraint = predicate;
 
  return requirement;
};
 
 
/**
* Tests to see if a given list of settings matches a set of filters exactly.
*
* @param array $settings The settings to check.
* @return boolean If any filter returns null, false. If there are any settings
* left over after all filters are processed, false. Otherwise true.
*/
exports.matchedSpecification = function (settings) {
  var constraints = Array.prototype.slice.call(arguments, 1, arguments.length);
 
  for (var constraint in constraints) {
    if (constraints.hasOwnProperty(constraint)) {
      var remainingSettings = constraints[constraint](settings);
 
      if (!remainingSettings) {
        return false;
      } else {
        settings = remainingSettings;
      }
    }
  }
 
  return azureUtil.objectKeysLength(settings) === 0;
};
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/services/storageserviceclient.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/services/storageserviceclient.js

Statements: 12.5% (69 / 552)      Branches: 0% (0 / 327)      Functions: 0% (0 / 78)      Lines: 12.59% (69 / 548)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340                                  1 1 1 1 1 1 1 1 1 1 1   1 1 1 1 1   1 1 1 1 1 1   1 1   1 1 1 1 1 1   1 1 1 1 1 1                           1                                                                                         1             1                                   1                                                                                                     1                             1                               1                                     1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         1                                                                                                                                                                                                                         1     1                                                                                                                                                                               1                                                                                         1                                         1 1                                                                                                                 1                                           1                                                                 1                         1                                                 1                                           1                                                                     1                                                                                                           1                                                                                           1                                                                                                                           1                         1                                         1                                   1                                             1                                                               1                           1                     1                   1    
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var request = require('request');
var url = require('url');
var qs = require('querystring');
var util = require('util');
var xml2js = require('xml2js');
var events = require('events');
var _ = require('underscore');
var guid = require('node-uuid');
var os = require('os');
var extend = require('extend');
var Parser = require('json-edm-parser');
 
var Md5Wrapper = require('../md5-wrapper');
var azureutil = require('../util/util');
var validate = require('../util/validate');
var SR = require('../util/sr');
var WebResource = require('../http/webresource');
 
var ServiceSettings = require('./servicesettings');
var StorageServiceSettings = require('./storageservicesettings');
var Constants = require('../util/constants');
var StorageUtilities = require('../util/storageutilities');
var ServicePropertiesResult = require('../models/servicepropertiesresult');
var TableUtilities = require('../../services/table/tableutilities');
 
var SharedKey = require('../signing/sharedkey');
var SharedAccessSignature = require('../signing/sharedaccesssignature');
 
var HeaderConstants = Constants.HeaderConstants;
var QueryStringConstants = Constants.QueryStringConstants;
var HttpResponseCodes = Constants.HttpConstants.HttpResponseCodes;
var StorageServiceClientConstants = Constants.StorageServiceClientConstants;
var defaultRequestLocationMode = Constants.RequestLocationMode.PRIMARY_ONLY;
var RequestLocationMode = Constants.RequestLocationMode;
 
var Logger = require('../diagnostics/logger');
var errors = require('../errors/errors');
var ArgumentError = errors.ArgumentError;
var ArgumentNullError = errors.ArgumentNullError;
var TimeoutError = errors.TimeoutError;
var StorageError = errors.StorageError;
 
/**
* Creates a new StorageServiceClient object.
*
* @class
* The StorageServiceClient class is the base class of all the service classes.
* @constructor
* @param {string} storageAccount           The storage account.
* @param {string} storageAccessKey         The storage access key.
* @param {object} host                     The host for the service.
* @param {bool}   usePathStyleUri          Boolean value indicating wether to use path style uris.
* @param {string} sasToken                 The Shared Access Signature token.
*/
function StorageServiceClient(storageAccount, storageAccessKey, host, usePathStyleUri, sasToken) {
  StorageServiceClient['super_'].call(this);
 
  if(storageAccount && storageAccessKey) {
    // account and key
    this.storageAccount = storageAccount;
    this.storageAccessKey = storageAccessKey;
    this.storageCredentials = new SharedKey(this.storageAccount, this.storageAccessKey, usePathStyleUri);
  } else if (sasToken) {
    // sas
    this.sasToken = sasToken;
    this.storageCredentials = new SharedAccessSignature(sasToken);
  } else {
    // anonymous
    this.anonymous = true;
    this.storageCredentials = {
      signRequest: function(webResource, callback){
        // no op, anonymous access
        callback(null);
      }
    };
  }
 
  if(host){
    this.setHost(host);
  }
 
  this.apiVersion = HeaderConstants.TARGET_STORAGE_VERSION;
  this.usePathStyleUri = usePathStyleUri;
 
  this._initDefaultFilter();
 
  /**
   * The logger of the service. To change the log level of the services, set the `[logger.level]{@link Logger#level}`.
   * @name StorageServiceClient#logger
   * @type Logger
   * */
  this.logger = new Logger(Logger.LogLevels.INFO);
 
  this._setDefaultProxy();
 
  this.xml2jsSettings = StorageServiceClient._getDefaultXml2jsSettings();
  this.defaultLocationMode = StorageUtilities.LocationMode.PRIMARY_ONLY;
}
 
util.inherits(StorageServiceClient, events.EventEmitter);
 
/**
* Gets the default xml2js settings.
* @ignore
* @return {object} The default settings
*/
StorageServiceClient._getDefaultXml2jsSettings = function() {
  var xml2jsSettings = _.clone(xml2js.defaults['0.2']);
 
  // these determine what happens if the xml contains attributes
  xml2jsSettings.attrkey = Constants.TableConstants.XML_METADATA_MARKER;
  xml2jsSettings.charkey = Constants.TableConstants.XML_VALUE_MARKER;
 
  // from xml2js guide: always put child nodes in an array if true; otherwise an array is created only if there is more than one.
  xml2jsSettings.explicitArray = false;
 
  return xml2jsSettings;
};
 
/**
* Sets a host for the service.
* @ignore
* @param {string}     host                              The host for the service.
*/
StorageServiceClient.prototype.setHost = function (host) {
  var parseHost = function(hostUri){
    var parsedHost;
    if(!azureutil.objectIsNull(hostUri)) {
      if(hostUri.indexOf('http') === -1 && hostUri.indexOf('//') !== 0){
        hostUri = '//' + hostUri;
      }
      parsedHost = url.parse(hostUri, false, true);
 
      if(!parsedHost.protocol){
        parsedHost.protocol = ServiceSettings.DEFAULT_PROTOCOL;
      }
 
      if (!parsedHost.port) {
        if (parsedHost.protocol === Constants.HTTPS) {
          parsedHost.port = Constants.DEFAULT_HTTPS_PORT;
        } else {
          parsedHost.port = Constants.DEFAULT_HTTP_PORT;
        }
      }
 
      parsedHost = url.format({
        protocol: parsedHost.protocol,
        port: parsedHost.port,
        hostname: parsedHost.hostname,
        pathname: parsedHost.pathname
      });
    }
 
    return parsedHost;
  };
 
  validate.isValidHost(host);
 
  this.host = {
    primaryHost: parseHost(host.primaryHost),
    secondaryHost: parseHost(host.secondaryHost)
  };
};
 
/**
* Performs a REST service request through HTTP expecting an input stream.
* @ignore
*
* @param {WebResource} webResource                        The webresource on which to perform the request.
* @param {string}      outputData                         The outgoing request data as a raw string.
* @param {object}      [options]                          The request options.
* @param {int}         [options.timeoutIntervalInMs]      The timeout interval, in milliseconds, to use for the request.
* @param {int}         [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {function}    callback                           The response callback function.
*/
StorageServiceClient.prototype.performRequest = function (webResource, outputData, options, callback) {
  this._performRequest(webResource, { outputData: outputData }, options, callback);
};
 
/**
* Performs a REST service request through HTTP expecting an input stream.
* @ignore
*
* @param {WebResource} webResource                        The webresource on which to perform the request.
* @param {Stream}      outputStream                       The outgoing request data as a stream.
* @param {object}      [options]                          The request options.
* @param {int}         [options.timeoutIntervalInMs]      The timeout interval, in milliseconds, to use for the request.
* @param {int}         [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {function}    callback                           The response callback function.
*/
StorageServiceClient.prototype.performRequestOutputStream = function (webResource, outputStream, options, callback) {
  this._performRequest(webResource, { outputStream: outputStream }, options, callback);
};
 
/**
* Performs a REST service request through HTTP expecting an input stream.
* @ignore
*
* @param {WebResource} webResource                        The webresource on which to perform the request.
* @param {string}      outputData                         The outgoing request data as a raw string.
* @param {Stream}      inputStream                        The ingoing response data as a stream.
* @param {object}      [options]                          The request options.
* @param {int}         [options.timeoutIntervalInMs]      The timeout interval, in milliseconds, to use for the request.
* @param {int}         [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {function}    callback                           The response callback function.
*/
StorageServiceClient.prototype.performRequestInputStream = function (webResource, outputData, inputStream, options, callback) {
  this._performRequest(webResource, { outputData: outputData, inputStream: inputStream }, options, callback);
};
 
/**
* Performs a REST service request through HTTP.
* @ignore
*
* @param {WebResource} webResource                        The webresource on which to perform the request.
* @param {object}      body                               The request body.
* @param {string}      [body.outputData]                  The outgoing request data as a raw string.
* @param {Stream}      [body.outputStream]                The outgoing request data as a stream.
* @param {Stream}      [body.inputStream]                 The ingoing response data as a stream.
* @param {object}      [options]                          The request options.
* @param {string}      [options.clientRequestId]          A string that represents the client request ID with a 1KB character limit.
* @param {int}         [options.timeoutIntervalInMs]      The timeout interval, in milliseconds, to use for the request.
* @param {int}         [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {function}    callback                           The response callback function.
*/
StorageServiceClient.prototype._performRequest = function (webResource, body, options, callback) {
  var self = this;
 
  // Sets a requestId on the webResource
  if(!options.clientRequestId) {
    options.clientRequestId = guid.v1();
  }
  
  webResource.withHeader(HeaderConstants.CLIENT_REQUEST_ID, options.clientRequestId);
 
  // Sets the user-agent string
  var userAgentComment = util.format('(NODE-VERSION %s; %s %s)', process.version, os.type(), os.release());
  webResource.withHeader(HeaderConstants.USER_AGENT, Constants.USER_AGENT_PRODUCT_NAME + '/' + Constants.USER_AGENT_PRODUCT_VERSION + ' ' + userAgentComment);
 
  // Initialize the location that the request is going to be sent to.
  if(azureutil.objectIsNull(options.locationMode)) {
    options.locationMode = this.defaultLocationMode;
  }
 
  // Initialize the location that the request can be sent to.
  if(azureutil.objectIsNull(options.requestLocationMode)) {
    options.requestLocationMode = defaultRequestLocationMode;
  }
 
  // Initialize whether nagling is used or not.
  if(azureutil.objectIsNull(options.useNagleAlgorithm)) {
    options.useNagleAlgorithm = this.useNagleAlgorithm;
  }
 
  this._initializeLocation(options);
  
  // Initialize the operationExpiryTime
  this._setOperationExpiryTime(options);
 
  // If the output stream already got sent to server and got error back, 
  // we should NOT retry within the SDK as the stream data is not valid anymore if we retry directly.
  // And it's very hard for SDK to re-wind the stream.
  //
  // If users want to retry on this kind of error, they can implement their own logic to parse the response and 
  // determine if they need to re-prepare a stream and call our SDK API to retry.
  //
  // Currently for blobs/files with size greater than 32MB (DEFAULT_SINGLE_BLOB_PUT_THRESHOLD_IN_BYTES), 
  // we'll send the steam by chunk buffers which doesn't have this issue.
  var outputStreamSent = false;
 
  var operation = function (options, next) {
    self._validateLocation(options);
    var currentLocation = options.currentLocation;
    self._buildRequestOptions(webResource, body, options, function (err, finalRequestOptions) {
      if (err) {
        callback({ error: err, response: null }, function (finalRequestOptions, finalCallback) {
          finalCallback(finalRequestOptions);
        });
      } else {
        self.logger.log(Logger.LogLevels.DEBUG, 'FINAL REQUEST OPTIONS:\n' + util.inspect(finalRequestOptions));
 
        if(self._maximumExecutionTimeExceeded(Date.now(), options.operationExpiryTime)) {
          callback({ error: new TimeoutError(SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION), response: null }, function (finalRequestOptions, finalCallback) {
            finalCallback(finalRequestOptions);
          });
        } else {
          var processResponseCallback = function (error, response) {
            var responseObject;
 
            if (error) {
              responseObject = { error: error, response: null };
            } else {
              responseObject = self._processResponse(webResource, response, options);
              responseObject.contentMD5 = response.contentMD5;
              responseObject.length = response.length;
            }
 
            responseObject.operationEndTime = new Date();
            // Required for listing operations to make sure successive operations go to the same location.
            responseObject.targetLocation = currentLocation;
            responseObject.outputStreamSent = outputStreamSent;
 
            callback(responseObject, next);
          };
 
          var endResponse;
          var buildRequest = function (headersOnly, inputStream) {
            // Build request (if body was set before, request will process immediately, if not it'll wait for the piping to happen
            var requestStream;
 
            var requestWithDefaults;
            
            if(self.proxy) {
              if(requestWithDefaults === undefined) {
                requestWithDefaults = request.defaults({'proxy':self.proxy});
              }
            } else {
              requestWithDefaults = request;
            }
 
            if (headersOnly) {
              requestStream = requestWithDefaults(finalRequestOptions);
 
              requestStream.on('error', processResponseCallback);
              requestStream.on('response', function (response) {
                var isValid = WebResource.validResponse(response.statusCode);
                if (!isValid) {
                    // When getting invalid response, try to get the error message for future steps to extract the detailed error information
                    var contentLength = parseInt(response.headers['content-length']);
                    var errorMessageBuffer;
                    var index = 0;
                    if (contentLength !== undefined) {
                      errorMessageBuffer = new Buffer(contentLength);
                    }
                    
                    requestStream.on('data', function (data) {
                      if (contentLength !== undefined) {
                        data.copy(errorMessageBuffer, index);
                        index += data.length;
                      } else {
                        if (!errorMessageBuffer) {
                          errorMessageBuffer = data;
                        } else {
                          errorMessageBuffer = Buffer.concat([errorMessageBuffer, data]);
                        }
                      }
                    });
                    requestStream.on('end', function () {
                      if (errorMessageBuffer) {
                        // Strip the UTF8 BOM following the same ways as 'request' module
                        if (errorMessageBuffer.length > 3 &&
                          errorMessageBuffer[0] === 239 &&
                          errorMessageBuffer[1] === 187 &&
                          errorMessageBuffer[2] === 191) {
                          response.body = errorMessageBuffer.toString('utf8', 3);
                        } else {
                          response.body = errorMessageBuffer.toString('utf8');
                        }
                      }
                      processResponseCallback(null, response);
                    });
                } else {
                  // Only pipe to the destination stream when we get a valid response from service
                  // Error message should NOT be piped to the destination stream
                  if (inputStream) {
                    requestStream.pipe(inputStream);
                  }
 
                  var responseLength = 0;
                  var internalHash = new Md5Wrapper().createMd5Hash();
                  requestStream.on('data', function(data) {
                    responseLength += data.length;
                    internalHash.update(data);
                  });
                                  
                  response.on('end', function () {
                    // Calculate and set MD5 here
                    if(azureutil.objectIsNull(options.disableContentMD5Validation) || options.disableContentMD5Validation === false) {
                      response.contentMD5 = internalHash.digest('base64');
                    }
                      
                    response.length = responseLength;
                    endResponse = response;
                  });
                }
              });
            } else {
              requestStream = requestWithDefaults(finalRequestOptions, processResponseCallback);
            }
 
            //If useNagleAlgorithm is not set or the value is set and is false, setNoDelay is set to true.
            if (azureutil.objectIsNull(options.useNagleAlgorithm) || options.useNagleAlgorithm === false) {
              requestStream.on('request', function(httpRequest) {
                httpRequest.setNoDelay(true);
              });
            }
 
            // Workaround to avoid request from potentially setting unwanted (rejected) headers by the service
            var oldEnd = requestStream.end;
            requestStream.end = function () {
              if (finalRequestOptions.headers['content-length']) {
                requestStream.headers['content-length'] = finalRequestOptions.headers['content-length'];
              } else if (requestStream.headers['content-length']) {
                delete requestStream.headers['content-length'];
              }
 
              oldEnd.call(requestStream);
            };
 
            // Bubble events up -- This is when the request is going to be made.
            requestStream.on('response', function (response) {
              self.emit('receivedResponseEvent', response);
            });
 
            return requestStream;
          };
 
          if (body && body.outputData) {
            finalRequestOptions.body = body.outputData;
          }
 
          // Pipe any input / output streams
          if (body && body.inputStream) {
            body.inputStream.on('close', function () {
              if (endResponse) {
                processResponseCallback(null, endResponse);
                endResponse = null;
              }
            });
            body.inputStream.on('end', function () {
              if (endResponse) {
                processResponseCallback(null, endResponse);
                endResponse = null;
              }
            });
            body.inputStream.on('finish', function () {
              if (endResponse) {
                processResponseCallback(null, endResponse);
                endResponse = null;
              }
            });
            buildRequest(true, body.inputStream);
          } else if (body && body.outputStream) {
            var sendUnchunked = function () {
              var size = finalRequestOptions.headers['content-length'] ?
                finalRequestOptions.headers['content-length'] :
                Constants.BlobConstants.MAX_SINGLE_UPLOAD_BLOB_SIZE_IN_BYTES;
 
              var concatBuf = new Buffer(size);
              var index = 0;
 
              body.outputStream.on('data', function (d) {
                outputStreamSent = true;
                if(self._maximumExecutionTimeExceeded(Date.now(), options.operationExpiryTime)) {
                  processResponseCallback(new TimeoutError(SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION));
                } else {
                  d.copy(concatBuf, index);
                  index += d.length;
                }
              }).on('end', function () {
                var requestStream = buildRequest();
                requestStream.write(concatBuf);
                requestStream.end();
              });
              if (azureutil.isStreamPaused(body.outputStream)) {
                body.outputStream.resume();
              }
            };
 
            var sendStream = function () {
              // NOTE: workaround for an unexpected EPIPE exception when piping streams larger than 29 MB
              if (!azureutil.objectIsNull(finalRequestOptions.headers['content-length']) && finalRequestOptions.headers['content-length'] < 29 * 1024 * 1024) {
                body.outputStream.pipe(buildRequest());
                outputStreamSent = true;
 
                if (azureutil.isStreamPaused(body.outputStream)) {
                  body.outputStream.resume();
                }
              } else {
                sendUnchunked();
              }
            };
 
            if (!body.outputStream.readable) {
              // if the content length is zero, build the request and don't send a body
              if (finalRequestOptions.headers['content-length'] === 0) {
                buildRequest();
              } else {
                // otherwise, wait until we know the readable stream is actually valid before piping
                body.outputStream.on('open', function () {
                  sendStream();
                });
              }
            } else {
              sendStream();
            }
 
            // This catches any errors that happen while creating the readable stream (usually invalid names)
            body.outputStream.on('error', function (error) {
              processResponseCallback(error);
            });
          } else {
            buildRequest();
          }
        }
      }
    });
  };
 
  // The filter will do what it needs to the requestOptions and will provide a
  // function to be handled after the reply
  self.filter(options, function (postFiltersRequestOptions, nextPostCallback) {
    if(self._maximumExecutionTimeExceeded(Date.now() + postFiltersRequestOptions.retryInterval, postFiltersRequestOptions.operationExpiryTime)) {
      callback({ error: new TimeoutError(SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION), response: null}, function (postFiltersRequestOptions, finalCallback) {
        finalCallback(postFiltersRequestOptions);
      });
    } else {
      // If there is a filter, flow is:
      // filter -> operation -> process response
      if(postFiltersRequestOptions.retryContext) {
        var func = function() {
          operation(postFiltersRequestOptions, nextPostCallback);
        };
 
        // Sleep for retryInterval before making the request
        setTimeout(func, postFiltersRequestOptions.retryInterval);
      } else {
        // No retry policy filter specified
        operation(postFiltersRequestOptions, nextPostCallback);
      }
    }
  });
};
 
 
/**
* Builds the request options to be passed to the http.request method.
* @ignore
* @param {WebResource} webResource The webresource where to build the options from.
* @param {object}      options     The request options.
* @param {function(error, requestOptions)}  callback  The callback function.
*/
StorageServiceClient.prototype._buildRequestOptions = function (webResource, body, options, callback) {
  webResource.withHeader(HeaderConstants.STORAGE_VERSION, this.apiVersion);
  webResource.withHeader(HeaderConstants.MS_DATE, new Date().toUTCString());
  if (!webResource.headers[HeaderConstants.ACCEPT]) {
    webResource.withHeader(HeaderConstants.ACCEPT, 'application/atom+xml,application/xml');
  }
  webResource.withHeader(HeaderConstants.ACCEPT_CHARSET, 'UTF-8');
 
  // Browsers cache GET/HEAD requests by adding conditional headers such as 'IF_MODIFIED_SINCE' after Azure Storage 'Authorization header' calculation, 
  // which may result in a 403 authorization error. So add timestamp to GET/HEAD request URLs thus avoid the browser cache. 
  if (azureutil.isBrowser() && (
    webResource.method === Constants.HttpConstants.HttpVerbs.GET || 
    webResource.method === Constants.HttpConstants.HttpVerbs.HEAD)) {
    webResource.withQueryOption(HeaderConstants.FORCE_NO_CACHE_IN_BROWSER, new Date().getTime());
  }
 
  if(azureutil.objectIsNull(options.timeoutIntervalInMs)) {
    options.timeoutIntervalInMs = this.defaultTimeoutIntervalInMs;
  }
 
  if(azureutil.objectIsNull(options.clientRequestTimeoutInMs)) {
    options.clientRequestTimeoutInMs = this.defaultClientRequestTimeoutInMs;
  }
 
  if(!azureutil.objectIsNull(options.timeoutIntervalInMs) && options.timeoutIntervalInMs > 0) {
    webResource.withQueryOption(QueryStringConstants.TIMEOUT, Math.ceil(options.timeoutIntervalInMs / 1000));
  }
  
  if(options.accessConditions) {
    webResource.withHeader(HeaderConstants.IF_MATCH, options.accessConditions.EtagMatch);
    webResource.withHeader(HeaderConstants.IF_MODIFIED_SINCE, options.accessConditions.DateModifedSince);
    webResource.withHeader(HeaderConstants.IF_NONE_MATCH, options.accessConditions.EtagNonMatch);
    webResource.withHeader(HeaderConstants.IF_UNMODIFIED_SINCE, options.accessConditions.DateUnModifiedSince);
    webResource.withHeader(HeaderConstants.SEQUENCE_NUMBER_EQUAL, options.accessConditions.SequenceNumberEqual);
    webResource.withHeader(HeaderConstants.SEQUENCE_NUMBER_LESS_THAN, options.accessConditions.SequenceNumberLessThan);
    webResource.withHeader(HeaderConstants.SEQUENCE_NUMBER_LESS_THAN_OR_EQUAL, options.accessConditions.SequenceNumberLessThanOrEqual);
    webResource.withHeader(HeaderConstants.BLOB_CONDITION_MAX_SIZE, options.accessConditions.MaxBlobSize);
    webResource.withHeader(HeaderConstants.BLOB_CONDITION_APPEND_POSITION, options.accessConditions.MaxAppendPosition);
  }
 
  if(options.sourceAccessConditions) {
    webResource.withHeader(HeaderConstants.SOURCE_IF_MATCH, options.sourceAccessConditions.EtagMatch);
    webResource.withHeader(HeaderConstants.SOURCE_IF_MODIFIED_SINCE, options.sourceAccessConditions.DateModifedSince);
    webResource.withHeader(HeaderConstants.SOURCE_IF_NONE_MATCH, options.sourceAccessConditions.EtagNonMatch);
    webResource.withHeader(HeaderConstants.SOURCE_IF_UNMODIFIED_SINCE, options.sourceAccessConditions.DateUnModifiedSince);
  }
  
  if (!webResource.headers || webResource.headers[HeaderConstants.CONTENT_TYPE] === undefined) {
    // work around to add an empty content type header to prevent the request module from magically adding a content type.
    webResource.headers[HeaderConstants.CONTENT_TYPE] = '';
  } else if (webResource.headers && webResource.headers[HeaderConstants.CONTENT_TYPE] === null) {
    delete webResource.headers[HeaderConstants.CONTENT_TYPE];
  }
 
  if (!webResource.headers || webResource.headers[HeaderConstants.CONTENT_LENGTH] === undefined) {
    if (body && body.outputData) {
      webResource.withHeader(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(body.outputData, 'UTF8'));
    } else if (webResource.headers[HeaderConstants.CONTENT_LENGTH] === undefined) {
      webResource.withHeader(HeaderConstants.CONTENT_LENGTH, 0);
    }
  } else if (webResource.headers && webResource.headers[HeaderConstants.CONTENT_LENGTH] === null) {
    delete webResource.headers[HeaderConstants.CONTENT_LENGTH];
  }
 
  // Sets the request url in the web resource.
  this._setRequestUrl(webResource, options);
 
  this.emit('sendingRequestEvent', webResource);
 
  // Now that the web request is finalized, sign it
  this.storageCredentials.signRequest(webResource, function (error) {
    var requestOptions = null;
 
    if (!error) {
      var targetUrl = webResource.uri;
 
      requestOptions = {
        url: url.format(targetUrl),
        method: webResource.method,
        headers: webResource.headers,
        mode: 'disable-fetch'
      };
 
      if (options) {
        //set encoding of response data. If set to null, the body is returned as a Buffer
        requestOptions.encoding = options.responseEncoding;
      }
      
      if (options && options.clientRequestTimeoutInMs) {
        requestOptions.timeout = options.clientRequestTimeoutInMs;
      } else {
        requestOptions.timeout = Constants.DEFAULT_CLIENT_REQUEST_TIMEOUT_IN_MS; // 2 minutes
      }
    }
 
    callback(error, requestOptions);
  });
};
 
/**
* Process the response.
* @ignore
*
* @param {WebResource} webResource                The web resource that made the request.
* @param {Response}    response                   The response object.
* @param {Options}     options                    The response parsing options.
* @param {String}      options.payloadFormat      The payload format.
* @return The normalized responseObject.
*/
StorageServiceClient.prototype._processResponse = function (webResource, response, options) {
  var self = this;
 
  function convertRawHeadersToHeaders(rawHeaders) {
    var headers = {};
    if(!rawHeaders) {
      return undefined;
    }
 
    for(var i = 0; i < rawHeaders.length; i++) {
      var headerName;
      if (rawHeaders[i].indexOf(HeaderConstants.PREFIX_FOR_STORAGE_METADATA) === 0) {
        headerName = rawHeaders[i];
      } else {
        headerName = rawHeaders[i].toLowerCase();
      }
      headers[headerName] = rawHeaders[++i];
    }
 
    return headers;
  }
 
  var validResponse = WebResource.validResponse(response.statusCode);
  var rsp = StorageServiceClient._buildResponse(validResponse, response.body, convertRawHeadersToHeaders(response.rawHeaders) || response.headers, response.statusCode, response.md5);
  var responseObject;
 
  if (validResponse && webResource.rawResponse) {
    responseObject = { error: null, response: rsp };
  } else {
    // attempt to parse the response body, errors will be returned in rsp.error without modifying the body
    rsp = StorageServiceClient._parseResponse(rsp, self.xml2jsSettings, options);
 
    if (validResponse && !rsp.error) {
        responseObject = { error: null, response: rsp };
    } else {
      rsp.isSuccessful = false;
 
      if (response.statusCode < 400 || response.statusCode >= 500) {
        this.logger.log(Logger.LogLevels.DEBUG,
            'ERROR code = ' + response.statusCode + ' :\n' + util.inspect(rsp.body));
      }
 
      // responseObject.error should contain normalized parser errors if they occured in _parseResponse
      // responseObject.response.body should contain the raw response body in that case
      var errorBody = rsp.body;
      if(rsp.error) {
        errorBody = rsp.error;
        delete rsp.error;
      }
 
      if (!errorBody) {
        var code = Object.keys(HttpResponseCodes).filter(function (name) {
          if (HttpResponseCodes[name] === rsp.statusCode) {
            return name;
          }
        });
 
        errorBody = { error: { code: code[0] } };
      }
 
      var normalizedError = StorageServiceClient._normalizeError(errorBody, response);
      responseObject = { error: normalizedError, response: rsp };
    }
  }
 
  this.logger.log(Logger.LogLevels.DEBUG, 'RESPONSE:\n' + util.inspect(responseObject));
 
  return responseObject;
};
 
/**
* Associate a filtering operation with this StorageServiceClient. Filtering operations
* can include logging, automatically retrying, etc. Filter operations are objects
* that implement a method with the signature:
*
*     "function handle (requestOptions, next)".
*
* After doing its preprocessing on the request options, the method needs to call
* "next" passing a callback with the following signature:
* signature:
*
*     "function (returnObject, finalCallback, next)"
*
* In this callback, and after processing the returnObject (the response from the
* request to the server), the callback needs to either invoke next if it exists to
* continue processing other filters or simply invoke finalCallback otherwise to end
* up the service invocation.
*
* @param {Object} filter The new filter object.
* @return {StorageServiceClient} A new service client with the filter applied.
*/
StorageServiceClient.prototype.withFilter = function (newFilter) {
    // Create a new object with the same members as the current service
    var derived = _.clone(this);
 
    // If the current service has a filter, merge it with the new filter
    // (allowing us to effectively pipeline a series of filters)
    var parentFilter = this.filter;
    var mergedFilter = newFilter;
    if (parentFilter !== undefined) {
      // The parentFilterNext is either the operation or the nextPipe function generated on a previous merge
      // Ordering is [f3 pre] -> [f2 pre] -> [f1 pre] -> operation -> [f1 post] -> [f2 post] -> [f3 post]
      mergedFilter = function (originalRequestOptions, parentFilterNext) {
        newFilter.handle(originalRequestOptions, function (postRequestOptions, newFilterCallback) {
          // handle parent filter pre and get Parent filter post
          var next = function (postPostRequestOptions, parentFilterCallback) {
            // The parentFilterNext is the filter next to the merged filter.
            // For 2 filters, that'd be the actual operation.
            parentFilterNext(postPostRequestOptions, function (responseObject, responseCallback, finalCallback) {
              parentFilterCallback(responseObject, finalCallback, function (postResponseObject) {
                newFilterCallback(postResponseObject, responseCallback, finalCallback);
              });
            });
          };
 
          parentFilter(postRequestOptions, next);
        });
      };
    }
 
    // Store the filter so it can be applied in performRequest
    derived.filter = mergedFilter;
    return derived;
  };
 
/*
* Builds a response object with normalized key names.
* @ignore
*
* @param {Bool}     isSuccessful    Boolean value indicating if the request was successful
* @param {Object}   body            The response body.
* @param {Object}   headers         The response headers.
* @param {int}      statusCode      The response status code.
* @param {string}   md5             The response's content md5 hash.
* @return {Object} A response object.
*/
StorageServiceClient._buildResponse = function (isSuccessful, body, headers, statusCode, md5) {
  return {
    isSuccessful: isSuccessful,
    statusCode: statusCode,
    body: body,
    headers: headers,
    md5: md5
  };
};
 
/**
* Parses a server response body from XML or JSON into a JS object.
* This is done using the xml2js library.
* @ignore
*
* @param {object}     response                   The response object with a property "body" with a XML or JSON string content.
* @param {object}     xml2jsSettings             The XML to json settings.
* @param {Options}    options                    The response parsing options.
* @param {String}     options.payloadFormat      The payload format.
* @return {object} The same response object with the body part as a JS object instead of a XML or JSON string.
*/
StorageServiceClient._parseResponse = function (response, xml2jsSettings, options) {
  function parseXml(body) {
    var parsed;
    var parser = new xml2js.Parser(xml2jsSettings);
    parser.parseString(azureutil.removeBOM(body.toString()), function (err, parsedBody) {
      if (err) {
        var xmlError = new SyntaxError('EXMLFORMAT');
        xmlError.innerError = err;
        throw xmlError;
      } else { parsed = parsedBody; }
    });
 
    return parsed;
  }
 
  if (response.body && Buffer.byteLength(response.body.toString()) > 0) {
    var contentType = '';
    if (response.headers && response.headers['content-type']) {
      contentType = response.headers['content-type'].toLowerCase();
    }
 
    try {
      if (contentType.indexOf('application/json') !== -1) {
        if (options && options.payloadFormat && options.payloadFormat !== TableUtilities.PayloadFormat.NO_METADATA) {
          var parser = new Parser();
          parser.onValue = function (value) {
            response.body = value;
          };
          parser.write(response.body);
        } else {
          response.body = JSON.parse(response.body);
        }
      } else if (contentType.indexOf('application/xml') !== -1 || contentType.indexOf('application/atom+xml') !== -1) {
        response.body = parseXml(response.body);
      } else if (contentType.indexOf('text/html') !== -1) {
        response.body = response.body;
      } else {
        response.body = parseXml(response.body);
        // throw new SyntaxError(SR.CONTENT_TYPE_MISSING, null);
      }
    } catch (e) {
      response.error = e;
    }
  }
 
  return response;
};
 
/**
* Gets the storage settings.
*
* @param {string} [storageAccountOrConnectionString]  The storage account or the connection string.
* @param {string} [storageAccessKey]                  The storage access key.
* @param {string} [host]                              The host address.
* @param {object} [sasToken]                          The sas token.
*
* @return {StorageServiceSettings}
*/
StorageServiceClient.getStorageSettings = function (storageAccountOrConnectionString, storageAccessKey, host, sasToken, endpointSuffix) {
  var storageServiceSettings;
  if (storageAccountOrConnectionString && !storageAccessKey && !sasToken) {
    // If storageAccountOrConnectionString was passed and no accessKey was passed, assume connection string
    storageServiceSettings = StorageServiceSettings.createFromConnectionString(storageAccountOrConnectionString);
  } else if ((storageAccountOrConnectionString && storageAccessKey) || sasToken || host) {
    // Account and key or credentials or anonymous
    storageServiceSettings = StorageServiceSettings.createExplicitly(storageAccountOrConnectionString, storageAccessKey, host, sasToken, endpointSuffix);
  } else {
    // Use environment variables
    storageServiceSettings = StorageServiceSettings.createFromEnvironment();
  }
 
  return storageServiceSettings;
};
 
/**
* Sets the webResource's requestUrl based on the service client settings.
* @ignore
*
* @param {WebResource} webResource The web resource where to set the request url.
*/
StorageServiceClient.prototype._setRequestUrl = function (webResource, options) {
  // Normalize the path
  // Backup the original path of the webResource to make sure it works fine even this function get executed multiple times - like RetryFilter
  webResource.originalPath = webResource.originalPath || webResource.path;
  webResource.path = this._getPath(webResource.originalPath);
 
  if(!this.host){
    throw new ArgumentNullError('this.host', SR.STORAGE_HOST_LOCATION_REQUIRED);
  }
 
  var host = this.host.primaryHost;
 
  if(!azureutil.objectIsNull(options) && options.currentLocation === Constants.StorageLocation.SECONDARY) {
    host = this.host.secondaryHost;
  }
 
  if(host && host.lastIndexOf('/') !== (host.length - 1)){
    host = host + '/';
  }
  
  var fullPath = url.format({pathname: webResource.path, query: webResource.queryString});
  webResource.uri = url.resolve(host, fullPath);
  webResource.path = url.parse(webResource.uri).pathname;
};
 
/**
* Retrieves the normalized path to be used in a request.
* It also removes any leading "/" of the path in case
* it's there before.
* @ignore
* @param {string} path The path to be normalized.
* @return {string} The normalized path.
*/
StorageServiceClient.prototype._getPath = function (path) {
  if (path === null || path === undefined) {
    path = '';
  } else if (path.indexOf('/') === 0) {
    path = path.substring(1);
  }
 
  return path;
};
 
/**
 * Get the url of a given path
 */
StorageServiceClient.prototype._getUrl = function (path, sasToken, primary) {
  var host;
  if (!azureutil.objectIsNull(primary) && primary === false) {
    host = this.host.secondaryHost;
  } else {
    host = this.host.primaryHost;
  }
 
  host = azureutil.trimPortFromUri(host);
  if(host && host.lastIndexOf('/') !== (host.length - 1)){
    host = host + '/';
  }
 
  var query = qs.parse(sasToken);
  var fullPath = url.format({ pathname: this._getPath(path), query: query });
  return url.resolve(host, fullPath);
};
 
/**
* Initializes the default filter.
* This filter is responsible for chaining the pre filters request into the operation and, after processing the response,
* pass it to the post processing filters. This method should only be invoked by the StorageServiceClient constructor.
* @ignore
*
*/
StorageServiceClient.prototype._initDefaultFilter = function () {
  this.filter = function (requestOptions, nextPreCallback) {
    if (nextPreCallback) {
      // Handle the next pre callback and pass the function to be handled as post call back.
      nextPreCallback(requestOptions, function (returnObject, finalCallback, nextPostCallback) {
        if (nextPostCallback) {
          nextPostCallback(returnObject);
        } else if (finalCallback) {
          finalCallback(returnObject);
        }
      });
    }
  };
};
 
/**
* Retrieves the metadata headers from the response headers.
* @ignore
*
* @param {object} headers The metadata headers.
* @return {object} An object with the metadata headers (without the "x-ms-" prefix).
*/
StorageServiceClient.prototype.parseMetadataHeaders = function (headers) {
  var metadata = {};
 
  if (!headers) {
    return metadata;
  }
 
  for (var header in headers) {
    if (header.indexOf(HeaderConstants.PREFIX_FOR_STORAGE_METADATA) === 0) {
      var key = header.substr(HeaderConstants.PREFIX_FOR_STORAGE_METADATA.length, header.length - HeaderConstants.PREFIX_FOR_STORAGE_METADATA.length);
      metadata[key] = headers[header];
    }
  }
  
  return metadata;
};
 
/**
* Gets the properties of a storage account’s service, including Azure Storage Analytics.
* @ignore
*
* @this {StorageServiceClient}
* @param {object}       [options]                               The request options.
* @param {LocationMode} [options.locationMode]                  Specifies the location mode used to decide which location the request should be sent to. 
*                                                               Please see StorageUtilities.LocationMode for the possible values.
* @param {int}          [options.timeoutIntervalInMs]           The server timeout interval, in milliseconds, to use for the request.
* @param {int}          [options.clientRequestTimeoutInMs]      The timeout of client requests, in milliseconds, to use for the request.
* @param {int}          [options.maximumExecutionTimeInMs]      The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                               The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                               execution time is checked intermittently while performing requests, and before executing retries.
* @param {bool}         [options.useNagleAlgorithm]             Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                               The default value is false.
* @param {errorOrResult}  callback                              `error` will contain information if an error occurs; otherwise, `result` will contain the properties 
*                                                               and `response` will contain information related to this operation.
*/
StorageServiceClient.prototype.getAccountServiceProperties = function (optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  
  validate.validateArgs('getServiceProperties', function (v) {
    v.callback(callback);
  });
  
  var options = extend(true, {}, userOptions);
  
  var webResource = WebResource.get()
    .withQueryOption(QueryStringConstants.COMP, 'properties')
    .withQueryOption(QueryStringConstants.RESTYPE, 'service');
  
  options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY;
  
  var processResponseCallback = function (responseObject, next) {
    responseObject.servicePropertiesResult = null;
    if (!responseObject.error) {
      responseObject.servicePropertiesResult = ServicePropertiesResult.parse(responseObject.response.body.StorageServiceProperties);
    }
    
    // function to be called after all filters
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.servicePropertiesResult, returnObject.response);
    };
    
    // call the first filter
    next(responseObject, finalCallback);
  };
  
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Sets the properties of a storage account’s service, including Azure Storage Analytics.
* You can also use this operation to set the default request version for all incoming requests that do not have a version specified.
*
* @this {StorageServiceClient}
* @param {object}             serviceProperties                        The service properties.
* @param {object}             [options]                                The request options.
* @param {LocationMode}       [options.locationMode]                   Specifies the location mode used to decide which location the request should be sent to. 
*                                                                      Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]            The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]       The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]       The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                      The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                      execution time is checked intermittently while performing requests, and before executing retries.
* @param {bool}               [options.useNagleAlgorithm]              Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                      The default value is false.
* @param {errorOrResponse}    callback                                 `error` will contain information
*                                                                      if an error occurs; otherwise, `response`
*                                                                      will contain information related to this operation.
*/
StorageServiceClient.prototype.setAccountServiceProperties = function (serviceProperties, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  
  validate.validateArgs('setServiceProperties', function (v) {
    v.object(serviceProperties, 'serviceProperties');
    v.callback(callback);
  });
  
  var options = extend(true, {}, userOptions);
  var servicePropertiesXml = ServicePropertiesResult.serialize(serviceProperties);
  
  var webResource = WebResource.put()
    .withQueryOption(QueryStringConstants.COMP, 'properties')
    .withQueryOption(QueryStringConstants.RESTYPE, 'service')
    .withHeader(HeaderConstants.CONTENT_TYPE, 'application/xml;charset="utf-8"')
    .withHeader(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(servicePropertiesXml))
    .withBody(servicePropertiesXml);
  
  var processResponseCallback = function (responseObject, next) {
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.response);
    };
    
    next(responseObject, finalCallback);
  };
  
  this.performRequest(webResource, webResource.body, options, processResponseCallback);
};
 
// Other functions
 
/**
* Processes the error body into a normalized error object with all the properties lowercased.
*
* Error information may be returned by a service call with additional debugging information:
* http://msdn.microsoft.com/en-us/library/windowsazure/dd179382.aspx
*
* Table services returns these properties lowercased, example, "code" instead of "Code". So that the user
* can always expect the same format, this method lower cases everything.
*
* @ignore
*
* @param {Object} error The error object as returned by the service and parsed to JSON by the xml2json.
* @return {Object} The normalized error object with all properties lower cased.
*/
StorageServiceClient._normalizeError = function (error, response) {
  if (azureutil.objectIsString(error)) {
    return new StorageError(error, null);
  } else if (error) {
    var normalizedError = {};
 
    // blob/queue errors should have error.Error, table errors should have error['odata.error']
    var errorProperties = error.Error || error.error || error['odata.error'] || error['m:error'] || error;
    normalizedError.code = errorProperties.message; // The message exists when there is error.Error.
    
    for (var property in errorProperties) {
      if (errorProperties.hasOwnProperty(property)) {
        var key = property.toLowerCase();
        if(key.indexOf('m:') === 0) {
          key = key.substring(2);
        }
        
        normalizedError[key] = errorProperties[property];
 
        // if this is a table error, message is an object - flatten it to normalize with blob/queue errors
        // ex: "message":{"lang":"en-US","value":"The specified resource does not exist."} becomes message: "The specified resource does not exist."
        if (key === 'message' && _.isObject(errorProperties[property])) {
          if (errorProperties[property]['value']) {
            normalizedError[key] = errorProperties[property]['value'];
          }
        }
      }
    }
 
    // add status code and server request id if available
    if (response) {
      if (response.statusCode) {
        normalizedError.statusCode = response.statusCode;
      }
 
      if (response.headers && response.headers['x-ms-request-id']) {
        normalizedError.requestId = response.headers['x-ms-request-id'];
      }
    }
 
    var errorObject = new StorageError(normalizedError.code, normalizedError);
    return errorObject;
  }
 
  return null;
};
 
/*
* Sets proxy object specified by caller.
*
* @param {object}   proxy       proxy to use for tunneling
*                               {
*                                host: hostname
*                                port: port number
*                                proxyAuth: 'user:password' for basic auth
*                                headers: {...} headers for proxy server
*                                key: key for proxy server
*                                ca: ca for proxy server
*                                cert: cert for proxy server
*                               }
*                               if null or undefined, clears proxy
*/
StorageServiceClient.prototype.setProxy = function (proxy) {
  if (proxy) {
    this.proxy = proxy;
  } else {
    this.proxy = null;
  }
};
 
/**
* Sets the service host default proxy from the environment.
* Can be overridden by calling _setProxyUrl or _setProxy
*
*/
StorageServiceClient.prototype._setDefaultProxy = function () {
  var proxyUrl = StorageServiceClient._loadEnvironmentProxyValue();
  if (proxyUrl) {
    var parsedUrl = url.parse(proxyUrl);
    if (!parsedUrl.port) {
      parsedUrl.port = 80;
    }
    this.setProxy(parsedUrl);
  } else {
    this.setProxy(null);
  }
};
 
/*
* Loads the fields "useProxy" and respective protocol, port and url
* from the environment values HTTPS_PROXY and HTTP_PROXY
* in case those are set.
* @ignore
*
* @return {string} or null
*/
StorageServiceClient._loadEnvironmentProxyValue = function () {
  var proxyUrl = null;
  if (process.env[StorageServiceClientConstants.EnvironmentVariables.HTTPS_PROXY]) {
    proxyUrl = process.env[StorageServiceClientConstants.EnvironmentVariables.HTTPS_PROXY];
  } else if (process.env[StorageServiceClientConstants.EnvironmentVariables.HTTPS_PROXY.toLowerCase()]) {
    proxyUrl = process.env[StorageServiceClientConstants.EnvironmentVariables.HTTPS_PROXY.toLowerCase()];
  } else if (process.env[StorageServiceClientConstants.EnvironmentVariables.HTTP_PROXY]) {
    proxyUrl = process.env[StorageServiceClientConstants.EnvironmentVariables.HTTP_PROXY];
  } else if (process.env[StorageServiceClientConstants.EnvironmentVariables.HTTP_PROXY.toLowerCase()]) {
    proxyUrl = process.env[StorageServiceClientConstants.EnvironmentVariables.HTTP_PROXY.toLowerCase()];
  }
 
  return proxyUrl;
};
 
/**
* Initializes the location to which the operation is being sent to.
*/
StorageServiceClient.prototype._initializeLocation = function (options) {
  if(!azureutil.objectIsNull(options.locationMode)) {
    switch(options.locationMode) {
    case StorageUtilities.LocationMode.PRIMARY_ONLY:
    case StorageUtilities.LocationMode.PRIMARY_THEN_SECONDARY:
      options.currentLocation = Constants.StorageLocation.PRIMARY;
      break;
    case StorageUtilities.LocationMode.SECONDARY_ONLY:
    case StorageUtilities.LocationMode.SECONDARY_THEN_PRIMARY:
      options.currentLocation = Constants.StorageLocation.SECONDARY;
      break;
    default:
      throw new RangeError(util.format(SR.ARGUMENT_OUT_OF_RANGE_ERROR, 'locationMode', options.locationMode));
    }
  } else {
    options.locationMode = StorageUtilities.LocationMode.PRIMARY_ONLY;
    options.currentLocation = Constants.StorageLocation.PRIMARY;
  }
};
 
/**
* Validates the location to which the operation is being sent to.
*/
StorageServiceClient.prototype._validateLocation = function (options) {
  if(this._invalidLocationMode(options.locationMode)) {
    throw new ArgumentNullError('host', SR.STORAGE_HOST_MISSING_LOCATION);
  }
 
  switch(options.requestLocationMode) {
  case Constants.RequestLocationMode.PRIMARY_ONLY:
    if(options.locationMode === StorageUtilities.LocationMode.SECONDARY_ONLY) {
      throw new ArgumentError('host.primaryHost', SR.PRIMARY_ONLY_COMMAND);
    }
 
    options.currentLocation = Constants.StorageLocation.PRIMARY;
    options.locationMode = StorageUtilities.LocationMode.PRIMARY_ONLY;
    break;
 
  case Constants.RequestLocationMode.SECONDARY_ONLY:
    if(options.locationMode === StorageUtilities.LocationMode.PRIMARY_ONLY) {
      throw new ArgumentError('host.secondaryHost', SR.SECONDARY_ONLY_COMMAND);
    }
 
    options.currentLocation = Constants.StorageLocation.SECONDARY;
    options.locationMode = StorageUtilities.LocationMode.SECONDARY_ONLY;
    break;
 
  default:
   // no op
  }
};
 
/**
* Checks whether we have the relevant host information based on the locationMode.
*/
StorageServiceClient.prototype._invalidLocationMode = function (locationMode) {
  switch(locationMode) {
  case StorageUtilities.LocationMode.PRIMARY_ONLY:
    return azureutil.objectIsNull(this.host.primaryHost);
  case StorageUtilities.LocationMode.SECONDARY_ONLY:
    return azureutil.objectIsNull(this.host.secondaryHost);
  default:
    return (azureutil.objectIsNull(this.host.primaryHost) || azureutil.objectIsNull(this.host.secondaryHost));
  }
};
 
/**
* Checks to see if the maximum execution timeout provided has been exceeded.
*/
StorageServiceClient.prototype._maximumExecutionTimeExceeded = function (currentTime, expiryTime) {
  if(!azureutil.objectIsNull(expiryTime) && currentTime > expiryTime) {
    return true;
  } else {
    return false;
  }
};
 
/**
* Sets the operation expiry time.
*/
StorageServiceClient.prototype._setOperationExpiryTime = function (options) {
  if(azureutil.objectIsNull(options.operationExpiryTime)) {
    if(!azureutil.objectIsNull(options.maximumExecutionTimeInMs)) {
      options.operationExpiryTime = Date.now() + options.maximumExecutionTimeInMs;
    } else if(this.defaultMaximumExecutionTimeInMs) {
      options.operationExpiryTime = Date.now() + this.defaultMaximumExecutionTimeInMs;
    }
  }
};
 
module.exports = StorageServiceClient;
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/services/storageservicesettings.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/services/storageservicesettings.js

Statements: 25% (31 / 124)      Branches: 0% (0 / 63)      Functions: 0% (0 / 9)      Lines: 25% (31 / 124)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421                                    1 1   1 1 1 1 1 1 1   1 1 1 1 1 1   1         1         1         1         1         1                                                   1                                                       1                             1   1                                                   1                                                   1                                                                                                                                                                                                                   1                                                                                               1                                                                                                                                                             1   1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
'use strict';
 
var _ = require('underscore');
var url = require('url');
 
var util = require('../util/util');
var ServiceSettings = require('./servicesettings');
var Constants = require('../util/constants');
var StorageServiceClientConstants = Constants.StorageServiceClientConstants;
var ConnectionStringKeys = Constants.ConnectionStringKeys;
var Validate = require('../util/validate');
var SR = require('../util/sr');
 
var useDevelopmentStorageSetting = ServiceSettings.setting(ConnectionStringKeys.USE_DEVELOPMENT_STORAGE_NAME, true);
var developmentStorageProxyUriSetting = ServiceSettings.settingWithFunc(ConnectionStringKeys.DEVELOPMENT_STORAGE_PROXY_URI_NAME, Validate.isValidUri);
var defaultEndpointsProtocolSetting = ServiceSettings.setting(ConnectionStringKeys.DEFAULT_ENDPOINTS_PROTOCOL_NAME, 'http', 'https');
var accountNameSetting = ServiceSettings.setting(ConnectionStringKeys.ACCOUNT_NAME_NAME);
var accountKeySetting = ServiceSettings.settingWithFunc(ConnectionStringKeys.ACCOUNT_KEY_NAME, Validate.isBase64Encoded);
var sasSetting = ServiceSettings.settingWithFunc(ConnectionStringKeys.SHARED_ACCESS_SIGNATURE_NAME, _.isString);
 
var blobEndpointSetting = ServiceSettings.settingWithFunc(
  ConnectionStringKeys.BLOB_ENDPOINT_NAME,
  Validate.isValidHost
);
 
var queueEndpointSetting = ServiceSettings.settingWithFunc(
  ConnectionStringKeys.QUEUE_ENDPOINT_NAME,
  Validate.isValidHost
);
 
var tableEndpointSetting = ServiceSettings.settingWithFunc(
  ConnectionStringKeys.TABLE_ENDPOINT_NAME,
  Validate.isValidHost
);
 
var fileEndpointSetting = ServiceSettings.settingWithFunc(
  ConnectionStringKeys.FILE_ENDPOINT_NAME,
  Validate.isValidHost
);
 
var endpointSuffixSetting = ServiceSettings.settingWithFunc(
  ConnectionStringKeys.ENDPOINT_SUFFIX_NAME,
  Validate.isValidHost
);
 
var validKeys = [
  ConnectionStringKeys.USE_DEVELOPMENT_STORAGE_NAME,
  ConnectionStringKeys.DEVELOPMENT_STORAGE_PROXY_URI_NAME,
  ConnectionStringKeys.DEFAULT_ENDPOINTS_PROTOCOL_NAME,
  ConnectionStringKeys.ACCOUNT_NAME_NAME,
  ConnectionStringKeys.ACCOUNT_KEY_NAME,
  ConnectionStringKeys.SHARED_ACCESS_SIGNATURE_NAME,
  ConnectionStringKeys.BLOB_ENDPOINT_NAME,
  ConnectionStringKeys.QUEUE_ENDPOINT_NAME,
  ConnectionStringKeys.TABLE_ENDPOINT_NAME,
  ConnectionStringKeys.FILE_ENDPOINT_NAME,
  ConnectionStringKeys.ENDPOINT_SUFFIX_NAME
];
 
/**
* Creates new storage service settings instance.
*
* @param {string} name                      The storage service name.
* @param {string} key                       The storage service key.
* @param {string} sasToken                  The storage service shared access signature token.
* @param {string} blobEndpoint              The storage service blob endpoint.
* @param {string} queueEndpoint             The storage service queue endpoint.
* @param {string} tableEndpoint             The storage service table endpoint.
* @param {string} fileEndpoint              The storage service file endpoint.
* @param {bool}   usePathStyleUri           Boolean value indicating wether to use path style uri or not.
*/
function StorageServiceSettings(name, key, sasToken, blobEndpoint, queueEndpoint, tableEndpoint, fileEndpoint, usePathStyleUri) {
  this._name = name;
  this._key = key;
 
  if (sasToken && sasToken[0] === '?') {
    this._sasToken = sasToken.slice(1);
  } else {
    this._sasToken = sasToken;
  }
 
  this._blobEndpoint = blobEndpoint;
  this._queueEndpoint = queueEndpoint;
  this._tableEndpoint = tableEndpoint;
  this._fileEndpoint = fileEndpoint;
 
  if (usePathStyleUri) {
    this._usePathStyleUri = usePathStyleUri;
  } else {
    this._usePathStyleUri = false;
  }
}
 
/**
* Creates a StorageServiceSettings object from the given connection string.
*
* @param {string} connectionString The storage settings connection string.
* @return {StorageServiceSettings}
*/
StorageServiceSettings.createFromConnectionString = function (connectionString) {
  var tokenizedSettings = ServiceSettings.parseAndValidateKeys(connectionString, validKeys);
 
  try {
    return StorageServiceSettings.createFromSettings(tokenizedSettings);
  } catch (e) {
    if (e instanceof ServiceSettings.NoMatchError) {
      // Replace no match settings exception by no match connection string one.
      ServiceSettings.noMatchConnectionString(connectionString);
    } else {
      throw e;
    }
  }
};
 
StorageServiceSettings.createExplicitly = function (storageAccount, storageAccessKey, host, sasToken, endpointSuffix) {
  var settings = {};
  function addIfNotNullOrEmpty(key, value){
    if(typeof value === 'string' && !util.stringIsEmpty(value)){
      settings[key] = value;
    } else if (typeof value == 'object' && !util.objectIsNull(value)) {
      settings[key] = value;
    }
  }
 
  // Endpoints
  if (host) {
    addIfNotNullOrEmpty('blobendpoint', host);
    addIfNotNullOrEmpty('tableendpoint', host);
    addIfNotNullOrEmpty('queueendpoint', host);
    addIfNotNullOrEmpty('fileendpoint', host);
  } else {
    addIfNotNullOrEmpty('defaultendpointsprotocol', ServiceSettings.DEFAULT_PROTOCOL.split(':', 1)[0]);
  }
 
  addIfNotNullOrEmpty('accountname', storageAccount);
  addIfNotNullOrEmpty('accountkey', storageAccessKey);
  addIfNotNullOrEmpty('sharedaccesssignature', sasToken);
  addIfNotNullOrEmpty('endpointsuffix', endpointSuffix);
 
  return StorageServiceSettings.createFromSettings(settings);
};
 
StorageServiceSettings.createFromEnvironment = function () {
  var emulated = process.env[StorageServiceClientConstants.EnvironmentVariables.EMULATED];
  if (emulated) {
    return StorageServiceSettings.getDevelopmentStorageAccountSettings();
  } 
 
  var connectionString = process.env[StorageServiceClientConstants.EnvironmentVariables.AZURE_STORAGE_CONNECTION_STRING];
  if (connectionString) {
    return StorageServiceSettings.createFromConnectionString(connectionString);
  } 
 
  var storageAccount = process.env[StorageServiceClientConstants.EnvironmentVariables.AZURE_STORAGE_ACCOUNT];
  var storageAccessKey = process.env[StorageServiceClientConstants.EnvironmentVariables.AZURE_STORAGE_ACCESS_KEY];
  if(storageAccount && storageAccessKey){
    return StorageServiceSettings.createExplicitly(storageAccount, storageAccessKey, null, null, null);
  }
 
  throw new Error(SR.NO_CREDENTIALS_PROVIDED);
};
 
/**
* Creates a StorageServiceSettings object from a set of settings.
*
* @param {object} settings The settings object.
* @return {StorageServiceSettings}
*/
StorageServiceSettings.createFromSettings = function (settings) {
  // Devstore case
  var matchedSpecs = ServiceSettings.matchedSpecification(
    settings,
    ServiceSettings.allRequired(useDevelopmentStorageSetting),
    ServiceSettings.optional(developmentStorageProxyUriSetting)
  );
 
  if (matchedSpecs) {
    var proxyUri = util.tryGetValueInsensitive(
      ConnectionStringKeys.DEVELOPMENT_STORAGE_PROXY_URI_NAME,
      settings
    );
 
    return this.getDevelopmentStorageAccountSettings(proxyUri);
  }
 
  // Account/Key automatic case
  matchedSpecs = ServiceSettings.matchedSpecification(
    settings,
    ServiceSettings.allRequired(
      defaultEndpointsProtocolSetting,
      accountNameSetting,
      accountKeySetting
    ), 
    ServiceSettings.optional(
      blobEndpointSetting,
      queueEndpointSetting,
      tableEndpointSetting,
      fileEndpointSetting,
      endpointSuffixSetting
    )
  );
 
  if (matchedSpecs) {  
    return this._createStorageServiceSettings(settings);
  }
 
  // Account/Key explicit case
  matchedSpecs = ServiceSettings.matchedSpecification(
    settings,
    ServiceSettings.allRequired(
      accountNameSetting,
      accountKeySetting
    ),
    ServiceSettings.atLeastOne(
      blobEndpointSetting,
      queueEndpointSetting,
      tableEndpointSetting,
      fileEndpointSetting,
      endpointSuffixSetting
    )
  );
 
  if (matchedSpecs) {  
    return this._createStorageServiceSettings(settings);
  }
 
  // SAS case
  matchedSpecs = ServiceSettings.matchedSpecification(
    settings,
    ServiceSettings.allRequired(
      sasSetting
    ),
    ServiceSettings.atLeastOne(
      blobEndpointSetting,
      queueEndpointSetting,
      tableEndpointSetting,
      fileEndpointSetting,
      endpointSuffixSetting
    )
  );
 
  if(matchedSpecs) {
    return this._createStorageServiceSettings(settings);
  }
 
  // anonymous explicit case
  // Only blob anonymous access is valid.
  matchedSpecs = ServiceSettings.matchedSpecification(
    settings,
    ServiceSettings.allRequired(
      blobEndpointSetting
    ),
    ServiceSettings.optional(
      fileEndpointSetting,
      queueEndpointSetting,
      tableEndpointSetting,
      endpointSuffixSetting
    )
  );
 
  if(matchedSpecs) {
    return this._createStorageServiceSettings(settings);
  }
 
  ServiceSettings.noMatchSettings(settings);
};
 
/**
* Returns a StorageServiceSettings with development storage credentials using
* the specified proxy Uri.
*
* @param {string} proxyUri The proxy endpoint to use.
* @return {StorageServiceSettings}
*/
StorageServiceSettings.getDevelopmentStorageAccountSettings = function (proxyUri) {
  if (!proxyUri) {
    proxyUri = StorageServiceClientConstants.DEV_STORE_URI;
  }
 
  var parsedUri = url.parse(proxyUri);
  var scheme = parsedUri.protocol;
  var host   = parsedUri.host;
  var prefix = scheme + '//' + host;
 
  var blobEndpoint = {
    primaryHost: prefix + ':10000' + '/' + StorageServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT,
    secondaryHost: prefix + ':10000' + '/' + StorageServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT + '-secondary'
  };
 
  var queueEndpoint = {
    primaryHost: prefix + ':10001' + '/' + StorageServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT,
    secondaryHost: prefix + ':10001' + '/' + StorageServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT + '-secondary'
  };
 
  var tableEndpoint = {
    primaryHost: prefix + ':10002' + '/' + StorageServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT,
    secondaryHost: prefix + ':10002' + '/' + StorageServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT + '-secondary'
  };
 
  return new StorageServiceSettings(
    StorageServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT,
    StorageServiceClientConstants.DEVSTORE_STORAGE_ACCESS_KEY,
    null,
    blobEndpoint,
    queueEndpoint,
    tableEndpoint,
    null,
    true
  );
};
 
/**
* Creates StorageServiceSettings object given endpoints uri.
*
* @ignore
* @param {array}  settings         The service settings.
* @param {string} blobEndpointUri  The blob endpoint uri.
* @param {string} queueEndpointUri The queue endpoint uri.
* @param {string} tableEndpointUri The table endpoint uri.
* @param {string} fileEndpointUri  The file endpoint uri.
* @return {StorageServiceSettings}
*/
StorageServiceSettings._createStorageServiceSettings = function (settings) {
  var standardizeHost = function (host, accountName, scheme, dns){
    var storageHost;
    if (host) {
      storageHost = {};
      storageHost.primaryHost = _.isString(host) ? host : host.primaryHost;
      storageHost.secondaryHost = _.isString(host) ? undefined : host.secondaryHost;
    }
 
    if (scheme && accountName && dns) {
      storageHost = storageHost ? storageHost : {};
      storageHost.primaryHost = storageHost.primaryHost ? storageHost.primaryHost : url.format({ protocol: scheme, hostname: accountName + '.' + dns});
      storageHost.secondaryHost = storageHost.secondaryHost ? storageHost.secondaryHost : url.format({ protocol: scheme, hostname: accountName + '-secondary.' + dns});
    }
 
    return storageHost;
  };
 
  var scheme = util.tryGetValueInsensitive(
    ConnectionStringKeys.DEFAULT_ENDPOINTS_PROTOCOL_NAME,
    settings
  );
 
  var accountName = util.tryGetValueInsensitive(
    ConnectionStringKeys.ACCOUNT_NAME_NAME,
    settings
  );
 
  var accountKey = util.tryGetValueInsensitive(
    ConnectionStringKeys.ACCOUNT_KEY_NAME,
    settings
  );
 
  var sasToken = util.tryGetValueInsensitive(
    ConnectionStringKeys.SHARED_ACCESS_SIGNATURE_NAME,
    settings
  );
 
  var endpointSuffix = util.tryGetValueInsensitive(
    ConnectionStringKeys.ENDPOINT_SUFFIX_NAME,
    settings
  );
 
  var blobEndpoint = standardizeHost(
      util.tryGetValueInsensitive(ConnectionStringKeys.BLOB_ENDPOINT_NAME, settings),
      accountName,
      scheme,
      endpointSuffix ? 'blob.' + endpointSuffix : StorageServiceClientConstants.CLOUD_BLOB_HOST);
 
  var queueEndpoint = standardizeHost(
      util.tryGetValueInsensitive(ConnectionStringKeys.QUEUE_ENDPOINT_NAME, settings),
      accountName,
      scheme,
      endpointSuffix ? 'queue.' + endpointSuffix : StorageServiceClientConstants.CLOUD_QUEUE_HOST);
 
  var tableEndpoint = standardizeHost(
      util.tryGetValueInsensitive(ConnectionStringKeys.TABLE_ENDPOINT_NAME, settings),
      accountName,
      scheme,
      endpointSuffix ? 'table.' + endpointSuffix : StorageServiceClientConstants.CLOUD_TABLE_HOST);
 
  var fileEndpoint = standardizeHost(
      util.tryGetValueInsensitive(ConnectionStringKeys.FILE_ENDPOINT_NAME, settings),
      accountName,
      scheme,
      endpointSuffix ? 'file.' + endpointSuffix : StorageServiceClientConstants.CLOUD_FILE_HOST);
 
 
  return new StorageServiceSettings(
    accountName,
    accountKey,
    sasToken,
    blobEndpoint,
    queueEndpoint,
    tableEndpoint,
    fileEndpoint
  );
};
 
StorageServiceSettings.validKeys = validKeys;
 
exports = module.exports = StorageServiceSettings;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/signing/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/signing/

Statements: 15.2% (31 / 204)      Branches: 0% (0 / 127)      Functions: 0% (0 / 25)      Lines: 15.27% (31 / 203)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/lib/common/signing/
File Statements Branches Functions Lines
hmacsha256sign.js 57.14% (4 / 7) 100% (0 / 0) 0% (0 / 2) 57.14% (4 / 7)
sharedaccesssignature.js 37.5% (6 / 16) 0% (0 / 4) 0% (0 / 2) 37.5% (6 / 16)
sharedkey.js 11.6% (21 / 181) 0% (0 / 123) 0% (0 / 21) 11.67% (21 / 180)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/signing/hmacsha256sign.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/signing/hmacsha256sign.js

Statements: 57.14% (4 / 7)      Branches: 100% (0 / 0)      Functions: 0% (0 / 2)      Lines: 57.14% (4 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44                                  1             1                     1             1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var crypto = require('crypto');
 
/**
* Creates a new HmacSHA256Sign object.
*
* @constructor
*/
function HmacSha256Sign(accessKey) {
  this._accessKey = accessKey;
  this._decodedAccessKey = new Buffer(this._accessKey, 'base64');
}
 
/**
* Computes a signature for the specified string using the HMAC-SHA256 algorithm.
*
* @param {string} stringToSign The UTF-8-encoded string to sign.
* @return A String that contains the HMAC-SHA256-encoded signature.
*/
HmacSha256Sign.prototype.sign = function (stringToSign) {
  // Encoding the Signature
  // Signature=Base64(HMAC-SHA256(UTF8(StringToSign)))
 
  return crypto.createHmac('sha256', this._decodedAccessKey).update(stringToSign, 'utf-8').digest('base64');
};
 
module.exports = HmacSha256Sign;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/signing/sharedaccesssignature.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/signing/sharedaccesssignature.js

Statements: 37.5% (6 / 16)      Branches: 0% (0 / 4)      Functions: 0% (0 / 2)      Lines: 37.5% (6 / 16)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58                              1 1 1               1                       1                                   1    
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
var HmacSha256Sign = require('./hmacsha256sign');
var Constants = require('./../util/constants');
var SR = require('./../util/sr');
 
/**
* Creates a new SharedAccessSignature object.
*
* @constructor
* @param {string} sasToken    The sasToken.
*/
function SharedAccessSignature(sasToken) {
  this.sasToken = sasToken;
  this.signer = new HmacSha256Sign(sasToken);
}
 
/**
* Signs a request with the signature header.
*
* @this {SharedAccessSignature}
* @param {WebResource} The webresource to be signed.
* @param {function(error)}  callback  The callback function.
*/
SharedAccessSignature.prototype.signRequest = function (webResource, callback) {
  if (webResource.uri.indexOf('?') === -1) {
    webResource.uri += '?';
  } else {
    webResource.uri += '&';
  }
 
  webResource.uri += this.sasToken;
 
  // Add the api-version
  if (this.sasToken.indexOf('api-version') == -1) {
    webResource.uri += '&' + Constants.QueryStringConstants.API_VERSION + '=' + Constants.HeaderConstants.TARGET_STORAGE_VERSION;
  } else {
    throw new SyntaxError(SR.INVALID_SAS_TOKEN);
  }
  callback(null);
};
 
module.exports = SharedAccessSignature;
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/signing/sharedkey.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/signing/sharedkey.js

Statements: 11.6% (21 / 181)      Branches: 0% (0 / 123)      Functions: 0% (0 / 21)      Lines: 11.67% (21 / 180)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501                                  1 1   1 1 1 1 1   1 1 1 1 1                   1                                                   1                                                                                                                                       1                                                                 1                                                                             1                                                                                       1                                                                                                         1                                                                                                                                                                                                                                                           1                                                                                                                                           1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var _ = require('underscore');
var qs = require('querystring');
 
var azureutil = require('../util/util');
var HmacSha256Sign = require('./hmacsha256sign');
var SR = require('../util/sr');
var errors = require('../errors/errors');
var ArgumentError = errors.ArgumentError;
 
var Constants = require('../util/constants');
var HeaderConstants = Constants.HeaderConstants;
var QueryStringConstants = Constants.QueryStringConstants;
var HeaderConstants = Constants.HeaderConstants;
var CompatibleVersionConstants = Constants.CompatibleVersionConstants;
 
/**
* Creates a new SharedKey object.
*
* @constructor
* @param {string} storageAccount    The storage account.
* @param {string} storageAccessKey  The storage account's access key.
* @param {bool}   usePathStyleUri   Boolean value indicating if the path, or the hostname, should include the storage account.
*/
function SharedKey(storageAccount, storageAccessKey, usePathStyleUri) {
  this.storageAccount = storageAccount;
  this.storageAccessKey = storageAccessKey;
  this.usePathStyleUri = usePathStyleUri;
  this.signer = new HmacSha256Sign(storageAccessKey);
}
 
/**
* Generates the shared access signature for a account.
* For more detailed information, refer to https://msdn.microsoft.com/en-us/library/azure/mt584140.aspx
*
* @param {object}                     sharedAccessPolicy                                The shared access policy.
* @param {SharedAccessServices}       sharedAccessPolicy.AccessPolicy.Services          The services (blob, file, queue, table) for a shared access signature associated with this shared access policy.
*                                                                                       Refer to `Constants.AccountSasConstants.Services`.
* @param {SharedAccessResourceTypes}  sharedAccessPolicy.AccessPolicy.ResourceTypes     The resource type for a shared access signature associated with this shared access policy.
*                                                                                       Refer to `Constants.AccountSasConstants.ResourceTypes`.
* @param {SharedAccessPermissions}    sharedAccessPolicy.AccessPolicy.Permissions       The permissions for a shared access signature. 
*                                                                                       Refer to `Constants.AccountSasConstants.Permissions`.
* @param {date}                       sharedAccessPolicy.AccessPolicy.Start             The time at which the Shared Access Signature becomes valid.
* @param {date}                       sharedAccessPolicy.AccessPolicy.Expiry            The time at which the Shared Access Signature becomes expired.
* @param {string}                     sharedAccessPolicy.AccessPolicy.IPAddressOrRange  An IP address or a range of IP addresses from which to accept requests. When specifying a range, note that the range is inclusive.
* @param {string}                     sharedAccessPolicy.AccessPolicy.Protocols         The protocols permitted for a request made with the account SAS. 
*                                                                                       Possible values are both HTTPS and HTTP (https,http) or HTTPS only (https). The default value is https,http. 
*                                                                                       Refer to `Constants.AccountSasConstants.Protocols`.
* @return {string} The shared access signature.
*/
SharedKey.prototype.generateAccountSignedQueryString = function (sharedAccessPolicy) {
  var addIfNotNull = function (queryString, name, value) {
    if (!azureutil.objectIsNull(name) && !azureutil.objectIsNull(value)) {
      queryString[name] = value;
    }
  };
 
  var formatAccessPolicyDates = function (accessPolicy) {
    if (!azureutil.objectIsNull(accessPolicy.Start)) {
      if (!_.isDate(accessPolicy.Start)) {
        accessPolicy.Start = new Date(accessPolicy.Start);
      }
 
      accessPolicy.Start = azureutil.truncatedISO8061Date(accessPolicy.Start);
    }
 
    if (!azureutil.objectIsNull(accessPolicy.Expiry)) {
      if (!_.isDate(accessPolicy.Expiry)) {
        accessPolicy.Expiry = new Date(accessPolicy.Expiry);
      }
 
      accessPolicy.Expiry = azureutil.truncatedISO8061Date(accessPolicy.Expiry);
    }
  };
 
  var queryString = {};
 
  addIfNotNull(queryString, QueryStringConstants.SIGNED_VERSION, HeaderConstants.TARGET_STORAGE_VERSION);
 
  // add shared access policy params
  if (sharedAccessPolicy.AccessPolicy) {
    formatAccessPolicyDates(sharedAccessPolicy.AccessPolicy);
 
    addIfNotNull(queryString, QueryStringConstants.SIGNED_SERVICES, sharedAccessPolicy.AccessPolicy.Services);
    addIfNotNull(queryString, QueryStringConstants.SIGNED_RESOURCE_TYPES, sharedAccessPolicy.AccessPolicy.ResourceTypes);
    addIfNotNull(queryString, QueryStringConstants.SIGNED_PERMISSIONS, sharedAccessPolicy.AccessPolicy.Permissions);
    addIfNotNull(queryString, QueryStringConstants.SIGNED_START, sharedAccessPolicy.AccessPolicy.Start);
    addIfNotNull(queryString, QueryStringConstants.SIGNED_EXPIRY, sharedAccessPolicy.AccessPolicy.Expiry);
    addIfNotNull(queryString, QueryStringConstants.SIGNED_IP, sharedAccessPolicy.AccessPolicy.IPAddressOrRange);
    addIfNotNull(queryString, QueryStringConstants.SIGNED_PROTOCOL, sharedAccessPolicy.AccessPolicy.Protocols);
  }
  
  // add signature
  addIfNotNull(queryString, QueryStringConstants.SIGNATURE, this._generateAccountSharedAccessSignature(sharedAccessPolicy));
 
  return qs.stringify(queryString);
};
 
 
/**
* Generates the signature part of the shared access signature for a account.
* For more detailed information, refer to https://msdn.microsoft.com/en-us/library/azure/mt584140.aspx
*
* @param {object}                     sharedAccessPolicy                                The shared access policy.
* @param {SharedAccessServices}       sharedAccessPolicy.AccessPolicy.Services          The services (blob, file, queue, table) for a shared access signature associated with this shared access policy.
*                                                                                       Refer to `Constants.AccountSasConstants.Services`.
* @param {SharedAccessResourceTypes}  sharedAccessPolicy.AccessPolicy.ResourceTypes     The resource type for a shared access signature associated with this shared access policy.
*                                                                                       Refer to `Constants.AccountSasConstants.ResourceTypes`.
* @param {SharedAccessPermissions}    sharedAccessPolicy.AccessPolicy.Permissions       The permissions for a shared access signature. 
*                                                                                       Refer to `Constants.AccountSasConstants.Permissions`.
* @param {date}                       sharedAccessPolicy.AccessPolicy.Start             The time at which the Shared Access Signature becomes valid.
* @param {date}                       sharedAccessPolicy.AccessPolicy.Expiry            The time at which the Shared Access Signature becomes expired.
* @param {string}                     sharedAccessPolicy.AccessPolicy.IPAddressOrRange  An IP address or a range of IP addresses from which to accept requests. When specifying a range, note that the range is inclusive.
* @param {string}                     sharedAccessPolicy.AccessPolicy.Protocols         The protocols permitted for a request made with the account SAS. 
*                                                                                       Possible values are both HTTPS and HTTP (https,http) or HTTPS only (https). The default value is https,http. 
*                                                                                       Refer to `Constants.AccountSasConstants.Protocols`.
* @return {string} The signature part of the shared access signature.
*/
SharedKey.prototype._generateAccountSharedAccessSignature = function(sharedAccessPolicy){
  var getvalueToAppend = function (value, noNewLine) {
    var returnValue = '';
    if (!azureutil.objectIsNull(value)) {
      returnValue = value;
    }
 
    if (noNewLine !== true) {
      returnValue += '\n';
    }
 
    return returnValue;
  };  
  
  var stringToSign = getvalueToAppend(this.storageAccount) +
      getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.Permissions : '') +
      getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.Services : '') +
      getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.ResourceTypes : '') +
      getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.Start : '') +
      getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.Expiry : '') +
      getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.IPAddressOrRange : '') +
      getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.Protocols : '') +
      getvalueToAppend(HeaderConstants.TARGET_STORAGE_VERSION);
      
  return this.signer.sign(stringToSign);  
};
 
/**
* Signs a request with the Authentication header.
*
* @param {WebResource} The webresource to be signed.
* @param {function(error)}  callback  The callback function.
*/
SharedKey.prototype.signRequest = function (webResource, callback) {
  var getvalueToAppend = function (value, headerName) {
    // Do not sign content-length 0 in 2014-08-16 and later
    if (headerName === HeaderConstants.CONTENT_LENGTH && (azureutil.objectIsNull(value[headerName]) || value[headerName].toString() === '0')) {
      return '\n';
    } else if (azureutil.objectIsNull(value) || azureutil.objectIsNull(value[headerName])) {
      return '\n';
    } else {
      return value[headerName] + '\n';
    }
  };
 
  var stringToSign =
    webResource.method + '\n' +
    getvalueToAppend(webResource.headers, HeaderConstants.CONTENT_ENCODING) +
    getvalueToAppend(webResource.headers, HeaderConstants.CONTENT_LANGUAGE) +
    getvalueToAppend(webResource.headers, HeaderConstants.CONTENT_LENGTH) +
    getvalueToAppend(webResource.headers, HeaderConstants.CONTENT_MD5) +
    getvalueToAppend(webResource.headers, HeaderConstants.CONTENT_TYPE) +
    getvalueToAppend(webResource.headers, HeaderConstants.DATE) +
    getvalueToAppend(webResource.headers, HeaderConstants.IF_MODIFIED_SINCE) +
    getvalueToAppend(webResource.headers, HeaderConstants.IF_MATCH) +
    getvalueToAppend(webResource.headers, HeaderConstants.IF_NONE_MATCH) +
    getvalueToAppend(webResource.headers, HeaderConstants.IF_UNMODIFIED_SINCE) +
    getvalueToAppend(webResource.headers, HeaderConstants.RANGE) +
    this._getCanonicalizedHeaders(webResource) +
    this._getCanonicalizedResource(webResource);
 
  var signature = this.signer.sign(stringToSign);
 
  webResource.withHeader(HeaderConstants.AUTHORIZATION, 'SharedKey ' + this.storageAccount + ':' + signature);
  callback(null);
};
 
/*
* Retrieves the webresource's canonicalized resource string.
* @param {WebResource} webResource The webresource to get the canonicalized resource string from.
* @return {string} The canonicalized resource string.
*/
SharedKey.prototype._getCanonicalizedResource = function (webResource) {
  var path = '/';
  if (webResource.path) {
    path = webResource.path;
  }
 
  var canonicalizedResource = '/' + this.storageAccount + path;
 
  // Get the raw query string values for signing
  var queryStringValues = webResource.queryString;
 
  // Build the canonicalized resource by sorting the values by name.
  if (queryStringValues) {
    var paramNames = [];
    Object.keys(queryStringValues).forEach(function (n) {
      paramNames.push(n);
    });
 
    paramNames = paramNames.sort();
    Object.keys(paramNames).forEach(function (name) {
      canonicalizedResource += '\n' + paramNames[name] + ':' + queryStringValues[paramNames[name]];
    });
  }
 
  return canonicalizedResource;
};
 
/*
* Constructs the Canonicalized Headers string.
*
* To construct the CanonicalizedHeaders portion of the signature string,
* follow these steps: 1. Retrieve all headers for the resource that begin
* with x-ms-, including the x-ms-date header. 2. Convert each HTTP header
* name to lowercase. 3. Sort the headers lexicographically by header name,
* in ascending order. Each header may appear only once in the
* string. 4. Unfold the string by replacing any breaking white space with a
* single space. 5. Trim any white space around the colon in the header. 6.
* Finally, append a new line character to each canonicalized header in the
* resulting list. Construct the CanonicalizedHeaders string by
* concatenating all headers in this list into a single string.
*
* @param {object} The webresource object.
* @return {string} The canonicalized headers.
*/
SharedKey.prototype._getCanonicalizedHeaders = function (webResource) {
  // Build canonicalized headers
  var canonicalizedHeaders = '';
  if (webResource.headers) {
    var canonicalizedHeadersArray = [];
    for (var header in webResource.headers) {
      if (header.indexOf(HeaderConstants.PREFIX_FOR_STORAGE) === 0) {
        var headerItem = { canonicalized: header.toLowerCase(), original: header };
        canonicalizedHeadersArray.push(headerItem);
      }
    }
 
    canonicalizedHeadersArray.sort(function(a, b) { return a.canonicalized.localeCompare(b.canonicalized); });
 
    _.each(canonicalizedHeadersArray, function (currentHeaderItem) {
      var value = webResource.headers[currentHeaderItem.original];
      if (!azureutil.IsNullOrEmptyOrUndefinedOrWhiteSpace(value)) {
        canonicalizedHeaders += currentHeaderItem.canonicalized + ':' + value + '\n';
      } else {
        canonicalizedHeaders += currentHeaderItem.canonicalized + ':\n';
      }
    });
  }
 
  return canonicalizedHeaders;
};
 
/**
* Generates the query string for a shared access signature signing.
*
* @this {SharedAccessSignature}
* @param {string}                     serviceType                                         The service type.
* @param {string}                     path                                                The path to the resource.
* @param {object}                     sharedAccessPolicy                                  The shared access policy.
* @param {string}                     [sharedAccessPolicy.Id]                             The signed identifier.
* @param {SharedAccessPermissions}    [sharedAccessPolicy.AccessPolicy.Permissions]       The permission type.
* @param {date}                       [sharedAccessPolicy.AccessPolicy.Start]             The time at which the Shared Access Signature becomes valid.
* @param {date}                       [sharedAccessPolicy.AccessPolicy.Expiry]            The time at which the Shared Access Signature becomes expired.
* @param {string}                     [sharedAccessPolicy.AccessPolicy.IPAddressOrRange]  An IP address or a range of IP addresses from which to accept requests. When specifying a range, note that the range is inclusive.
* @param {string}                     [sharedAccessPolicy.AccessPolicy.Protocols]         The protocols permitted for a request made with the account SAS. 
*                                                                                         Possible values are both HTTPS and HTTP (https,http) or HTTPS only (https). The default value is https,http. 
* @param {string}                     sasVersion                                          A string indicating the desired SAS Version to use, in storage service version format. Value must be 2012-02-12 or later.
* @parma {ResourceTypes}              [args.resourceType]                                 The resource type, if the resource is a blob or container.  Null if the resource is a queue or table.
* @parma {ResourceTypes}              [args.tableName]                                    The table name, if the resource is a table.  Null if the resource is a blob orqueue.
* @parma {ResourceTypes}              [args.queryString]                                  The query string, if additional parameters are desired.
* @param {object}                     [args.headers]                                      The optional header values to set for a blob returned wth this SAS.
* @param {string}                     [args.headers.CacheControl]                         The value of the Cache-Control response header to be returned when this SAS is used.
* @param {string}                     [args.headers.ContentType]                          The value of the Content-Type response header to be returned when this SAS is used.
* @param {string}                     [args.headers.ContentEncoding]                      The value of the Content-Encoding response header to be returned when this SAS is used.
* @param {string}                     [args.headers.ContentLanguage]                      The value of the Content-Language response header to be returned when this SAS is used.
* @param {string}                     [args.headers.ContentDisposition]                   The value of the Content-Disposition response header to be returned when this SAS is used.
* @return {object} The shared access signature query string.
*/
SharedKey.prototype.generateSignedQueryString = function (serviceType, path, sharedAccessPolicy, sasVersion, args) {
  var addIfNotNull = function (queryString, name, value) {
    if (!azureutil.objectIsNull(name) && !azureutil.objectIsNull(value)) {
      queryString[name] = value;
    }
  };
 
  var validateVersion = function (sasVersion) {
    // validate and add version
    if (azureutil.objectIsNull(sasVersion)) {
      return HeaderConstants.TARGET_STORAGE_VERSION;
    } else {
      var values = _.values(CompatibleVersionConstants);
      if (values.some(function(version) {
        return version.toLowerCase() === sasVersion.toLowerCase();
      })) {
        return sasVersion;
      } else {
        throw new ArgumentError('sasVersion', azureutil.stringFormat(SR.INVALID_SAS_VERSION, sasVersion, values));
      }
    }
  };
 
  var formatAccessPolicyDates = function (accessPolicy) {
    if (!azureutil.objectIsNull(accessPolicy.Start)) {
      if (!_.isDate(accessPolicy.Start)) {
        accessPolicy.Start = new Date(accessPolicy.Start);
      }
 
      accessPolicy.Start = azureutil.truncatedISO8061Date(accessPolicy.Start);
    }
 
    if (!azureutil.objectIsNull(accessPolicy.Expiry)) {
      if (!_.isDate(accessPolicy.Expiry)) {
        accessPolicy.Expiry = new Date(accessPolicy.Expiry);
      }
 
      accessPolicy.Expiry = azureutil.truncatedISO8061Date(accessPolicy.Expiry);
    }
  };
 
  // set up optional args
  var queryString;
  var resourceType;
  var headers;
  var tableName;
  
  if(args) {
    queryString = args.queryString;
    resourceType = args.resourceType;
    tableName = args.tableName;
    headers = args.headers;
  }
 
  if(!queryString) {
    queryString = {};
  }
 
  // add shared access policy params
  if (sharedAccessPolicy.AccessPolicy) {
    formatAccessPolicyDates(sharedAccessPolicy.AccessPolicy);
 
    addIfNotNull(queryString, QueryStringConstants.SIGNED_START, sharedAccessPolicy.AccessPolicy.Start);
    addIfNotNull(queryString, QueryStringConstants.SIGNED_EXPIRY, sharedAccessPolicy.AccessPolicy.Expiry);
    addIfNotNull(queryString, QueryStringConstants.SIGNED_PERMISSIONS, sharedAccessPolicy.AccessPolicy.Permissions);
    addIfNotNull(queryString, QueryStringConstants.SIGNED_IP, sharedAccessPolicy.AccessPolicy.IPAddressOrRange);
    addIfNotNull(queryString, QueryStringConstants.SIGNED_PROTOCOL, sharedAccessPolicy.AccessPolicy.Protocols);
 
    // tables only
    addIfNotNull(queryString, QueryStringConstants.STARTPK, sharedAccessPolicy.AccessPolicy.StartPk);
    addIfNotNull(queryString, QueryStringConstants.ENDPK, sharedAccessPolicy.AccessPolicy.EndPk);
    addIfNotNull(queryString, QueryStringConstants.STARTRK, sharedAccessPolicy.AccessPolicy.StartRk);
    addIfNotNull(queryString, QueryStringConstants.ENDRK, sharedAccessPolicy.AccessPolicy.EndRk);
  }
 
  // validate and add version
  var validatedSASVersionString = validateVersion(sasVersion);
  addIfNotNull(queryString, QueryStringConstants.SIGNED_VERSION, validatedSASVersionString);
 
  // add signed identifier
  addIfNotNull(queryString, QueryStringConstants.SIGNED_IDENTIFIER, sharedAccessPolicy.Id);
 
  // blobs only
  addIfNotNull(queryString, QueryStringConstants.SIGNED_RESOURCE, resourceType);
  if (headers) {
    addIfNotNull(queryString, QueryStringConstants.CACHE_CONTROL, headers.cacheControl);
    addIfNotNull(queryString, QueryStringConstants.CONTENT_TYPE, headers.contentType);
    addIfNotNull(queryString, QueryStringConstants.CONTENT_ENCODING, headers.contentEncoding);
    addIfNotNull(queryString, QueryStringConstants.CONTENT_LANGUAGE, headers.contentLanguage);
    addIfNotNull(queryString, QueryStringConstants.CONTENT_DISPOSITION, headers.contentDisposition);
  }
 
  // tables only
  addIfNotNull(queryString, QueryStringConstants.TABLENAME, tableName);
 
  // add signature
  addIfNotNull(queryString, QueryStringConstants.SIGNATURE, this._generateSignature(serviceType, path, sharedAccessPolicy, validatedSASVersionString, {resourceType: resourceType, headers: headers, tableName: tableName}));
 
  return qs.stringify(queryString);
};
 
/**
* Generates the shared access signature for a resource.
*
* @this {SharedAccessSignature}
* @param {string}                     serviceType                                         The service type.
* @param {string}                     path                                                The path to the resource.
* @param {object}                     sharedAccessPolicy                                  The shared access policy.
* @param {string}                     [sharedAccessPolicy.Id]                             The signed identifier.
* @param {SharedAccessPermissions}    [sharedAccessPolicy.AccessPolicy.Permissions]       The permission type.
* @param {date}                       [sharedAccessPolicy.AccessPolicy.Start]             The time at which the Shared Access Signature becomes valid.
* @param {date}                       [sharedAccessPolicy.AccessPolicy.Expiry]            The time at which the Shared Access Signature becomes expired.
* @param {string}                     [sharedAccessPolicy.AccessPolicy.IPAddressOrRange]  An IP address or a range of IP addresses from which to accept requests. When specifying a range, note that the range is inclusive.
* @param {string}                     [sharedAccessPolicy.AccessPolicy.Protocols]         The protocols permitted for a request made with the account SAS. 
*                                                                                         Possible values are both HTTPS and HTTP (https,http) or HTTPS only (https). The default value is https,http.
* @param {string}                     sasVersion                                          A string indicating the desired SAS Version to use, in storage service version format. Value must be 2012-02-12 or later.
* @parma {ResourceTypes}              [args.resourceType]                                 The resource type, if the resource is a blob or container.  Null if the resource is a queue or table.
* @parma {ResourceTypes}              [args.tableName]                                    The table name, if the resource is a table.  Null if the resource is a blob or queue.
* @param {object}                     [args.headers]                                      The optional header values to set for a blob returned wth this SAS.
* @param {string}                     [args.headers.CacheControl]                         The value of the Cache-Control response header to be returned when this SAS is used.
* @param {string}                     [args.headers.ContentType]                          The value of the Content-Type response header to be returned when this SAS is used.
* @param {string}                     [args.headers.ContentEncoding]                      The value of the Content-Encoding response header to be returned when this SAS is used.
* @param {string}                     [args.headers.ContentLanguage]                      The value of the Content-Language response header to be returned when this SAS is used.
* @param {string}                     [args.headers.ContentDisposition]                   The value of the Content-Disposition response header to be returned when this SAS is used.
* @return {string} The shared access signature.
*/
SharedKey.prototype._generateSignature = function (serviceType, path, sharedAccessPolicy, sasVersion, args) {
  var getvalueToAppend = function (value, noNewLine) {
    var returnValue = '';
    if (!azureutil.objectIsNull(value)) {
      returnValue = value;
    }
 
    if (noNewLine !== true) {
      returnValue += '\n';
    }
 
    return returnValue;
  };
 
  // set up optional args
  var resourceType;
  var tableName;
  var headers;
  if(args) {
    resourceType = args.resourceType;
    tableName = args.tableName;
    headers = args.headers;
  }
 
  // Add leading slash to path
  if (path.substr(0, 1) !== '/') {
    path = '/' + path;
  }
 
  var canonicalizedResource;
  if (sasVersion === CompatibleVersionConstants.FEBRUARY_2012 || sasVersion === CompatibleVersionConstants.AUGUST_2013) {
    // Do not prepend service name for older versions
    canonicalizedResource = '/' + this.storageAccount + path;
  } else {
    canonicalizedResource = '/' + serviceType + '/' + this.storageAccount + path;
  }
 
  var stringToSign = getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.Permissions : '') +
      getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.Start : '') +
      getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.Expiry : '') +
      getvalueToAppend(canonicalizedResource) +
      getvalueToAppend(sharedAccessPolicy.Id) +
      getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.IPAddressOrRange : '') +
      getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.Protocols : '') +
      sasVersion;
 
  if(sasVersion == CompatibleVersionConstants.FEBRUARY_2012) {
    if(headers) {
      throw new ArgumentError('args.headers', SR.INVALID_HEADERS);
    }
  } else if (resourceType) {
    stringToSign += '\n' +
    getvalueToAppend(headers ? headers.cacheControl : '') +
    getvalueToAppend(headers ? headers.contentDisposition : '') +
    getvalueToAppend(headers ? headers.contentEncoding : '') +
    getvalueToAppend(headers ? headers.contentLanguage : '') +
    getvalueToAppend(headers ? headers.contentType : '', true);
  }
 
  if(tableName) {
    stringToSign += '\n' + 
    getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.StartPk : '') +
    getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.StartRk : '') +
    getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.EndPk : '') +
    getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.EndRk : '', true);
  }
 
  return this.signer.sign(stringToSign);
};
 
module.exports = SharedKey;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/streams/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/streams/

Statements: 17.61% (140 / 795)      Branches: 0.3% (1 / 337)      Functions: 0% (0 / 99)      Lines: 17.9% (140 / 782)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/lib/common/streams/
File Statements Branches Functions Lines
batchoperation.js 19.9% (40 / 201) 1.18% (1 / 85) 0% (0 / 24) 20.2% (40 / 198)
chunkallocator.js 15% (6 / 40) 0% (0 / 20) 0% (0 / 5) 15.38% (6 / 39)
chunkstream.js 16.78% (24 / 143) 0% (0 / 68) 0% (0 / 17) 17.14% (24 / 140)
chunkstreamwithstream.js 33.33% (13 / 39) 0% (0 / 12) 0% (0 / 7) 33.33% (13 / 39)
filereadstream.js 18.97% (22 / 116) 0% (0 / 56) 0% (0 / 16) 19.13% (22 / 115)
rangestream.js 10.74% (16 / 149) 0% (0 / 53) 0% (0 / 15) 10.96% (16 / 146)
readablefs.js 42.86% (3 / 7) 0% (0 / 2) 0% (0 / 1) 42.86% (3 / 7)
speedsummary.js 16% (16 / 100) 0% (0 / 41) 0% (0 / 14) 16.33% (16 / 98)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/streams/batchoperation.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/streams/batchoperation.js

Statements: 19.9% (40 / 201)      Branches: 1.18% (1 / 85)      Functions: 0% (0 / 24)      Lines: 20.2% (40 / 198)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422                                1 1 1 1 1   1 1 1 1 1   1 1   1 1 1 1                     1                                                                     1                 1         1                     1                                 1                 1             1                           1                 1             1                   1                       1                                 1                                                                             1                                                                           1                               1                           1                                                       1             1                                                                     1         1                                                       1   1    
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var util = require('util');
var http = require('http');
var https = require('https');
var EventEmitter = require('events').EventEmitter;
var os = require('os');
 
var azureutil = require('../util/util');
var Logger = require('../diagnostics/logger');
var Constants = require('../util/constants');
var errors = require('../errors/errors');
var ArgumentError = errors.ArgumentError;
 
var DEFAULT_OPERATION_MEMORY_USAGE = Constants.BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES;
var DEFAULT_GLOBAL_CONCURRENCY = 5; //Default http connection limitation for nodejs
 
var SystemTotalMemory = os.totalmem();
var CriticalFreeMemory = 0.1 * SystemTotalMemory;
var nodeVersion = azureutil.getNodeVersion();
var enableReuseSocket = nodeVersion.major > 0 || nodeVersion.minor >= 10;
 
/**
* Concurrently execute batch operations and call operation callback randomly or in sequence.
* Random mode is for uploading.
*   1. Fire user callback when the operation is done.
* Sequence mode is for downloading.
*   1. Fire user callback when the operation is done and all previous operations and callback has finished.
*   2. BatchOperation guarantees the user callback is fired one by one.
*   3. The next user callback can't be fired until the current one is completed.
*/
function BatchOperation(name, options) {
  if (!options) {
    options = {};
  }
 
  this.name = name;
  this.logger = options.logger || new Logger(Logger.LogLevels.INFO);
  this.operationMemoryUsage = options.operationMemoryUsage || DEFAULT_OPERATION_MEMORY_USAGE;
  this.callbackInOrder = options.callbackInOrder === true;
  this.callInOrder = options.callInOrder === true;
  this._currentOperationId = this.callbackInOrder ? 1 : -1;
  this.concurrency = DEFAULT_GLOBAL_CONCURRENCY;
 
  this._emitter = new EventEmitter();
  this._enableComplete = false;
  this._ended = false;
  this._error = null;
  this._paused = false;
 
  //Total operations count(queued and active and connected)
  this._totalOperation = 0;
 
  //Action operations count(The operations which are connecting to remote or executing callback or queued for executing)
  this._activeOperation = 0;
 
  //Queued operations count(The operations which are connecting to remote or queued for executing)
  this._queuedOperation = 0;
 
  //finished operation should be removed from this array
  this._operations = [];
}
 
/**
* Operation state
*/
var OperationState = {
  INITED : 'inited',
  QUEUED : 'queued',
  RUNNING : 'running',
  COMPLETE : 'complete',
  CALLBACK : 'callback',
  ERROR : 'error'
};
 
BatchOperation.OperationState = OperationState;
 
/**
* Set batch operation concurrency
*/
BatchOperation.prototype.setConcurrency = function(concurrency) {
  if (concurrency) {
    this.concurrency = concurrency;
    http.Agent.maxSockets = this.concurrency;
    https.Agent.maxSockets = this.concurrency;
  }
};
 
/**
* Is the workload heavy and It can be used to determine whether we could queue operations
*/
BatchOperation.prototype.IsWorkloadHeavy = function() {
  //Only support one batch operation for now.
  //In order to work with the multiple batch operation, we can use global operation track objects
  //BatchOperation acquire a bunch of operation ids from global and allocated ids to RestOperation
  //RestOperation start to run in order of id
  var sharedRequest = 1;
  if(enableReuseSocket && !this.callInOrder) {
    sharedRequest = 2;
  }
  return this._activeOperation >= sharedRequest * this.concurrency ||
    this._isLowMemory() ||
    (this._activeOperation >= this.concurrency && this._getApproximateMemoryUsage() > 0.5 * SystemTotalMemory);
};
 
/**
* get the approximate memory usage for batch operation
*/
BatchOperation.prototype._getApproximateMemoryUsage = function() {
  var currentUsage = process.memoryUsage().rss;
  var futureUsage = this._queuedOperation * this.operationMemoryUsage;
  return currentUsage + futureUsage;
};
 
/**
* get the approximate free memory
*/
BatchOperation.prototype._isLowMemory = function() {
  return os.freemem() < CriticalFreeMemory;
};
 
/**
* Add a operation into batch operation
*/
BatchOperation.prototype.addOperation = function(operation) {
  this._operations.push(operation);
  operation.status = OperationState.QUEUED;
  operation.operationId = ++this._totalOperation;
  this._queuedOperation++;
  this.logger.debug(util.format('Add operation %d into batch operation %s. Active: %s; Queued: %s', operation.operationId, this.name, this._activeOperation, this._queuedOperation));
  //Immediately start the idle operation if workload isn't heavy
  this._runOperation(operation);
  return this.IsWorkloadHeavy();
};
 
/**
* Enable batch operation complete when there is no operation to run.
*/
BatchOperation.prototype.enableComplete = function() {
  this._enableComplete = true;
  this.logger.debug(util.format('Enable batch operation %s complete', this.name));
  this._tryEmitEndEvent();
};
 
/**
* Stop firing user call back
*/
BatchOperation.prototype.pause = function () {
  this._paused = true;
};
 
/**
* Start firing user call back
*/
BatchOperation.prototype.resume = function () {
  if (this._paused) {
    this._paused = false;
    this._fireOperationUserCallback();
  }
};
 
/**
* Add event listener
*/
BatchOperation.prototype.on = function(event, listener) {
  // only emit end if the batch has completed all operations
  if(this._ended && event === 'end') {
    listener();
  } else {
    this._emitter.on(event, listener);
  }
};
 
/**
* Run operation
*/
BatchOperation.prototype._runOperation = function (operation) {
  this.logger.debug(util.format('Operation %d start to run', operation.operationId));
  var cb = this.getBatchOperationCallback(operation);
 
  if(this._error) {
    cb(this._error);//Directly call the callback with previous error.
  } else {
    operation.run(cb);
  }
 
  this._activeOperation++;
};
 
/**
* Return an general operation call back.
* This callback is used to update the internal status and fire user's callback when operation is complete.
*/
BatchOperation.prototype.getBatchOperationCallback = function (operation) {
  var self = this;
  return function (error) {
    self._queuedOperation--;
    if (error) {
      operation.status = OperationState.ERROR;
      self.logger.debug(util.format('Operation %d failed. Error %s', operation.operationId, error));
      self._error = error;
    } else {
      operation.status = OperationState.CALLBACK;
      self.logger.debug(util.format('Operation %d succeed', operation.operationId));
    }
 
    operation._callbackArguments = arguments;
    if (self._paused) {
      operation.status = OperationState.CALLBACK;
      self.logger.debug(util.format('Batch operation paused and Operation %d wait for firing callback', operation.operationId));
    } else if (self.callbackInOrder) {
      operation.status = OperationState.CALLBACK;
      if (self._currentOperationId === operation.operationId) {
        self._fireOperationUserCallback(operation);
      } else if (self._currentOperationId > operation.operationId) {
        throw new Error('Debug error: current callback operation id cannot be larger than operation id');
      } else {
        self.logger.debug(util.format('Operation %d is waiting for firing callback %s', operation.operationId, self._currentOperationId));
      }
    } else {
      self._fireOperationUserCallback(operation);
    }
 
    self._tryEmitDrainEvent();
    operation = null;
    self = null;
  };
};
 
/**
* Fire user's call back
*/
BatchOperation.prototype._fireOperationUserCallback = function (operation) {
  var index = this._getCallbackOperationIndex();
  if (!operation && index != -1) {
    operation = this._operations[index];
  }
 
  if (operation && !this._paused) {
    // fire the callback, if exists
    if (operation._userCallback) {
      this.logger.debug(util.format('Fire user call back for operation %d', operation.operationId));
      // make sure UserCallback is a sync operation in sequence mode.
      // both async and sync operations are available for random mode.
      operation._fireUserCallback();
    }
    
    // remove the operation from the array and decrement the counter
    this._operations.splice(index, 1);
    this._activeOperation--;
    operation.status = OperationState.COMPLETE;
    index = operation = null;
 
    if (this.callbackInOrder) {
      this._currentOperationId++;
    }
 
    this._fireOperationUserCallback();
  } else if (this._paused) {
    this._tryEmitDrainEvent();
  } else {
    // check if batch has ended and if so emit end event
    this._tryEmitEndEvent();
  }
};
 
/**
* Try to emit the BatchOperation end event
* End event means all the operation and callback already finished.
*/
BatchOperation.prototype._tryEmitEndEvent = function () {
  if(this._enableComplete && this._activeOperation === 0 && this._operations.length === 0) {
    this._ended = true;
    this.logger.debug(util.format('Batch operation %s emits the end event', this.name));
    this._emitter.emit('end', this._error, null);
    return true;
  }
  
  // Workaround to recover from the 'hang' edge case. _tryEmitEndEvent function is not supposed to be called if the bacth is not really completed.
  this._tryEmitDrainEvent();
  return false;
};
 
/**
* Try to emit the drain event
*/
BatchOperation.prototype._tryEmitDrainEvent = function () {
  if (!this._emitter) return false;
  if(!this.IsWorkloadHeavy() || this._activeOperation < this.concurrency) {
    this._emitter.emit('drain');
    return true;
  }
  return false;
};
 
/**
* Get the current active operation index.
* Only the active operation could call user's callback in sequence model.
* The other finished but not active operations should wait for wake up.
*/
BatchOperation.prototype._getCallbackOperationIndex = function () {
  var operation = null;
  for (var i = 0; i < this._operations.length; i++) {
    operation = this._operations[i];
    if (this.callbackInOrder) {
      //Sequence mode
      if (operation.operationId == this._currentOperationId) {
        if (operation.status === OperationState.CALLBACK) {
          return i;
        } else {
          return -1;
        }
      }
    } else {
      //Random mode
      if (operation.status === OperationState.CALLBACK) {
        return i;
      }
    }
  }
  return -1;
};
 
/**
* Do nothing and directly call the callback.
* In random mode, the user callback will be called immediately
* In sequence mode, the user callback will be called after the previous callback has been called
*/
BatchOperation.noOperation = function (cb) {
  cb();
};
 
/**
* Rest operation in sdk
*/
function RestOperation(serviceClient, operation) {
  this.status = OperationState.Inited;
  this.operationId = -1;
  this._callbackArguments = null;
 
  // setup callback and args
  this._userCallback = arguments[arguments.length - 1];
  var sliceEnd = arguments.length;
  if(azureutil.objectIsFunction(this._userCallback)) {
    sliceEnd--;
  } else {
    this._userCallback = null;
  }
  var operationArguments = Array.prototype.slice.call(arguments).slice(2, sliceEnd);
 
  this.run = function(cb) {
    var func = serviceClient[operation];
    if(!func) {
      throw new ArgumentError('operation', util.format('Unknown operation %s in serviceclient', operation));
    } else {
      if(!cb) cb = this._userCallback;
      operationArguments.push(cb);
      this.status = OperationState.RUNNING;
      func.apply(serviceClient, operationArguments);
      operationArguments = operation = null;
    }
  };
 
  this._fireUserCallback = function () {
    if(this._userCallback) {
      this._userCallback.apply(null, this._callbackArguments);
    }
  };
}
 
BatchOperation.RestOperation = RestOperation;
 
/**
* Common operation wrapper
*/
function CommonOperation(operationFunc, callback) {
  this.status = OperationState.Inited;
  this.operationId = -1;
  this._callbackArguments = null;
  var sliceStart = 2;
  if (azureutil.objectIsFunction(callback)) {
    this._userCallback = callback;
  } else {
    this._userCallback = null;
    sliceStart = 1;
  }
  var operationArguments = Array.prototype.slice.call(arguments).slice(sliceStart);
  this.run = function (cb) {
    if (!cb) cb = this._userCallback;
    operationArguments.push(cb);
    this.status = OperationState.RUNNING;
    operationFunc.apply(null, operationArguments);
    operationArguments = operationFunc = null;
  };
  
  this._fireUserCallback = function () {
    if (this._userCallback) {
      this._userCallback.apply(null, this._callbackArguments);
    }
    this._userCallback = this._callbackArguments = null;
  };
}
 
BatchOperation.CommonOperation = CommonOperation;
 
module.exports = BatchOperation;
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/streams/chunkallocator.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/streams/chunkallocator.js

Statements: 15% (6 / 40)      Branches: 0% (0 / 20)      Functions: 0% (0 / 5)      Lines: 15.38% (6 / 39)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122                                        1                                     1                             1                                           1                                       1                                             1    
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
/**
* Chunked memory pool allocator.
* It could dramatically reduce the memory usage.
* However, it can't dramatically reduce the CPU time since GC in v8 is very efficient.
*/
function ChunkAllocator(chunkSize, maxCount) {
  // Track the unused buffers and number of used buffers
  this._pool = [];
  this._inuse = 0;
 
  // Buffer size
  this._chunkSize = chunkSize;
 
  // If total memory is larger than this._chunkSize * this._maxCount, the buffer pool is not used.
  this._maxCount = maxCount || 10;
 
  // Immediately add a buffer to the pool.
  this._extendMemoryPool();
}
 
/**
* Synchronously require a buffer
* Caller should be aware of that the content of buffer is random since the Buffer.fill is Time-consumed opreation.
*/
ChunkAllocator.prototype.getBuffer = function(size) {
  var buffer = this._getBufferFromPool(size);
  if (buffer === null) {
    // Either the total memory is larger than this._chunkSize * this._maxCount
    // Or, the size does not match the chunk size of the pool
    buffer = new Buffer(size);
  }
 
  this._inuse++;
  return buffer;
};
 
/**
* Get buffer from the current memory pool.
*/
ChunkAllocator.prototype._getBufferFromPool = function(size) {
  // Return null if the given size does not match the chunk size of the buffer pool.
  if(size !== this._chunkSize) {
    return null;
  } 
 
  // Extend the memory pool if it is empty.
  if(this._pool.length === 0) {
    this._extendMemoryPool();
  }
 
  // If the pool is not empty, return a buffer.
  if(this._pool.length !== 0) {
    return this._pool.pop();
  } else {
    return null;
  }
};
 
/**
* Extend the memory pool if the maximum size has not been reached.
*/
ChunkAllocator.prototype._extendMemoryPool = function() {
  var total = this._pool.length + this._inuse;
 
  // If the total is larger than the max, do not allocate more memory.
  if(total >= this._maxCount) return;
 
  // Calculate the new number of buffers, equal to the total*2 bounded by 1 and the maxCount
  var nextSize = Math.min(total * 2, this._maxCount) || 1;
 
  // Add more buffers.
  var increment = nextSize - total;
  for(var i = 0; i < increment; i++) {
    var buffer = new Buffer(this._chunkSize);
    this._pool.push(buffer);
  }
};
 
/**
* Release the buffer.
*/
ChunkAllocator.prototype.releaseBuffer = function(buffer) {
  if(buffer.length !== this._chunkSize) {
    // Directly delete the buffer if bufferSize is invalid and wait for GC.
    buffer = null;
    return;
  }
 
  // Add the buffer to the pool if it is not full, otherwise delete it
  if (this._pool.length < this._maxCount) {
    this._pool.push(buffer);
  } else {
    buffer = null;
  }
 
  // Decrement _inuse 
  this._inuse--;
 
  // _inuse could be below zero if a buffer is released which was not returned by getBuffer
  if(this._inuse < 0) {
    this._inuse = 0;
  }
};
 
module.exports = ChunkAllocator;
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/streams/chunkstream.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/streams/chunkstream.js

Statements: 16.78% (24 / 143)      Branches: 0% (0 / 68)      Functions: 0% (0 / 17)      Lines: 17.14% (24 / 140)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305                                1 1   1 1 1                   1                                                     1         1             1                 1                                               1           1           1               1                         1                                                                               1                                                                 1                                   1                   1                                     1                         1                                     1             1               1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var stream = require('stream');
var util = require('util');
 
var Md5Wrapper = require('../md5-wrapper');
var Constants = require('../util/constants');
var bufferSize = Constants.BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES;
 
/**
*  Chunk stream
*  1. Calculate md5
*  2. Track reading offset
*  3. Work with customize memory allocator
*  4. Buffer data from stream.
*  @param {object} options stream.Readable options
*/
function ChunkStream(options) {
  stream.Stream.call(this);
  this.writable = this.readable = true;
 
  if (!options) {
    options = {};
  }
 
  this._highWaterMark = options.highWaterMark || bufferSize;
 
  this._paused = undefined; //True/false is the external status from users.
 
  this._isStreamOpened = false;
  this._offset = 0;
  this._allocator = options.allocator;
  this._streamEnded = false;
  this._md5hash = null;
  this._buffer = null;
  this._internalBufferSize = 0;
  this._outputLengthLimit = 0;
  this._md5sum = undefined;
 
  if (options.calcContentMd5) {
    this._md5hash = new Md5Wrapper().createMd5Hash();
  }
}
 
util.inherits(ChunkStream, stream.Stream);
 
/**
* Set the memory allocator.
*/
ChunkStream.prototype.setMemoryAllocator = function(allocator) {
  this._allocator = allocator;
};
 
/**
* Set the output length.
*/
ChunkStream.prototype.setOutputLength = function(length) {
  if (length) {
    this._outputLengthLimit = length;
  }
};
 
/**
* Internal stream ended
*/
ChunkStream.prototype.end = function (chunk, encoding, cb) {
  if (typeof chunk === 'function') {
    cb = chunk;
    chunk = null;
    encoding = null;
  } else if (typeof encoding === 'function') {
    cb = encoding;
    encoding = null;
  }
 
  if (chunk) {
    this.write(chunk, encoding);
  }
 
  this._streamEnded = true;
  this._flushInternalBuffer();
  
  if (cb) {
    this.once('end', cb);
  }
 
  this.emit('end');
};
 
ChunkStream.prototype.finish = function () {
  this.emit('finish');
 
  this.destroy();
};
 
ChunkStream.prototype.error = function () {
  this.emit('error');
 
  this.destroy();
};
 
ChunkStream.prototype.destroy = function () {
  this.writable = this.readable = false;
  this.emit('close');
};
 
/**
* Add event listener
*/
ChunkStream.prototype.write = function (chunk, encoding) {
  if (!this._isStreamOpened) {
    this._isStreamOpened = true;
  }
 
  this._buildChunk(chunk, encoding);
 
  return !this._paused;
};
 
/**
* Buffer the data into a chunk and emit it
*/
ChunkStream.prototype._buildChunk = function (data) {
  if (typeof data == 'string') {
    data = new Buffer(data);
  }
  var dataSize = data.length;
  var dataOffset = 0;
  do {
    var buffer = null;
    var targetSize = this._internalBufferSize + dataSize;
 
    if (targetSize < this._highWaterMark) {
      // add the data to the internal buffer and return as it is not yet full
      this._copyToInternalBuffer(data, dataOffset, data.length);
      return;
    } else if (targetSize == this._highWaterMark){
      if(this._internalBufferSize === 0 && data.length === this._highWaterMark) {
        // set the buffer to the data passed in to avoid creating a new buffer
        buffer = data;
      } else {
        // add the data to the internal buffer and pop that buffer
        this._copyToInternalBuffer(data, dataOffset, data.length);
        buffer = this._popInternalBuffer();
      }
      dataSize = 0;
    } else {
      // add data to the internal buffer until its full, then return it
      // set the dataSize parameter so that additional data is not lost
      var copySize = this._highWaterMark - this._internalBufferSize;
      this._copyToInternalBuffer(data, dataOffset, dataOffset + copySize);
      dataSize -= copySize;
      dataOffset += copySize;
      buffer = this._popInternalBuffer();
    }
    this._emitBufferData(buffer);
  } while(dataSize > 0);
};
 
/**
* Emit the buffer
*/
ChunkStream.prototype._emitBufferData = function(buffer) {
  var newOffset = this._offset + buffer.length;
  var range = {
    start : this._offset,
    end : newOffset - 1,
    size : buffer.length
  };
 
  this._offset = newOffset;
  
  if (this._outputLengthLimit > 0) {
    // When the start postion is larger than the limit, no data will be consumed though there is an event to be emitted.
    // So the buffer should not be calculated.
    if (range.start <= this._outputLengthLimit) {
      if (this._offset > this._outputLengthLimit) {
        // Don't use negative end parameter which means the index starting from the end of the buffer
        // to be compatible with node 0.8.
        buffer = buffer.slice(0, buffer.length - (this._offset - this._outputLengthLimit));
      }
      if (this._md5hash) {
        this._md5hash.update(buffer);
      }
    }
  } else if (this._md5hash) {
    this._md5hash.update(buffer);
  }
 
  this.emit('data', buffer, range);
};
 
/**
* Copy data into internal buffer
*/
ChunkStream.prototype._copyToInternalBuffer = function(data, start, end) {
  if(start === undefined) start = 0;
  if(end === undefined) end = data.length;
  if (!this._buffer) {
    this._buffer = this._allocateNewBuffer();
    this._internalBufferSize = 0;
  }
  var copied = data.copy(this._buffer, this._internalBufferSize, start, end);
  this._internalBufferSize += copied;
 
  if(copied != (end - start)) {
    throw new Error('Can not copy entire data to buffer');
  }
};
 
/**
* Flush internal buffer
*/
ChunkStream.prototype._flushInternalBuffer = function() {
  var buffer = this._popInternalBuffer();
  if (buffer) {
    this._emitBufferData(buffer);
  }
};
 
/**
* Pop internal buffer
*/
ChunkStream.prototype._popInternalBuffer = function () {
  var buf = null;
  if (!this._buffer || this._internalBufferSize === 0) {
    buf = null;
  } else if(this._internalBufferSize == this._highWaterMark) {
    buf = this._buffer;
  } else {
    buf = this._buffer.slice(0, this._internalBufferSize);
  }
 
  this._buffer = null;
  this._internalBufferSize = 0;
 
  return buf;
};
 
/**
* Allocate a buffer
*/
ChunkStream.prototype._allocateNewBuffer = function() {
  var size = this._highWaterMark;
  if(this._allocator && this._allocator.getBuffer) {
    return this._allocator.getBuffer(size);
  } else {
    var buffer = new Buffer(size);
    return buffer;
  }
};
 
/**
* Get file content md5 when read completely.
*/
ChunkStream.prototype.getContentMd5 = function(encoding) {
  if (!encoding) encoding = 'base64';
  if(!this._md5hash) {
    throw new Error('Can\'t get content md5, please set the calcContentMd5 option for FileReadStream.');
  } else {
    if (this._streamEnded) {
      if (!this._md5sum) {
        this._md5sum = this._md5hash.digest(encoding);
      }
      return this._md5sum;
    } else {
      throw new Error('Stream has not ended.');
    }
  }
};
 
/**
* Pause chunk stream
*/
ChunkStream.prototype.pause = function() {
  this._paused = true;
};
 
/**
* Resume read stream
*/
ChunkStream.prototype.resume = function() {
  if (this._paused) {
    this._paused = false;
 
    this.emit('drain');
  }
};
 
module.exports = ChunkStream;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/streams/chunkstreamwithstream.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/streams/chunkstreamwithstream.js

Statements: 33.33% (13 / 39)      Branches: 0% (0 / 12)      Functions: 0% (0 / 7)      Lines: 33.33% (13 / 39)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105                                1 1 1 1                   1               1         1                                             1                       1                 1           1         1         1    
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var ChunkStream = require('./chunkstream');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var azureutil = require('./../util/util');
 
/**
*  Chunk stream
*  1. Calculate md5
*  2. Track reading offset
*  3. Work with customize memory allocator
*  4. Buffer data from stream.
*  @param {object} options stream.Readable options
*/
function ChunkStreamWithStream(stream, options) {
  ChunkStream.call(this, options);
 
  stream.pause(); // Pause stream and wait for data listener. It's useful for node v0.8
  this._stream = stream;
  this._stream.on('end', this.end.bind(this)); // Should catch the end event for node v0.8
}
 
util.inherits(ChunkStreamWithStream, ChunkStream);
 
/**
* Add event listener
*/
ChunkStreamWithStream.prototype.on = function(event, listener) {
  if(event === 'end' && this._streamEnded) {
    listener(); //Directly call the end event when stream already ended
  } else {
    EventEmitter.prototype.on.call(this, event, listener);
  }
 
  if (event === 'data') {
    if (!this._isStreamOpened) {
      this._isStreamOpened = true;
      this._stream.on('data', this._buildChunk.bind(this));
    }
    if (this._paused === undefined) {
      this._stream.resume();
    }
  }
  
  return this;
};
 
/**
* Stop stream from external
*/
ChunkStreamWithStream.prototype.stop = function (chunk, encoding, cb) {
  if (azureutil.objectIsFunction(this._stream.destroy)) {
    this._stream.destroy();
  } else {
    this.pause();
  }
  ChunkStream.prototype.end.call(this, chunk, encoding, cb);
};
 
/**
* Pause chunk stream
*/
ChunkStreamWithStream.prototype.pause = function () {
  ChunkStream.prototype.pause.call(this);
 
  this._stream.pause();
};
 
/**
* Resume read stream
*/
ChunkStreamWithStream.prototype.resume = function() {
  ChunkStream.prototype.resume.call(this);
 
  this._stream.resume();
};
 
ChunkStreamWithStream.prototype.finish = function () {
  ChunkStream.prototype.finish.call(this);
  this._stream.emit.call(this._stream, 'finish');
};
 
ChunkStreamWithStream.prototype.destroy = function () {
  ChunkStream.prototype.destroy.call(this);
  this._stream.emit.call(this._stream, 'close');
};
 
module.exports = ChunkStreamWithStream;
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/streams/filereadstream.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/streams/filereadstream.js

Statements: 18.97% (22 / 116)      Branches: 0% (0 / 56)      Functions: 0% (0 / 16)      Lines: 19.13% (22 / 115)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250                                1 1 1 1   1 1 1   1                   1                                                       1         1                               1                       1                       1                 1                                                                                                                   1                                     1             1                       1       1               1                                           1    
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var stream = require('stream');
var util = require('util');
var fs = require('fs');
var validator = require('validator');
 
var Md5Wrapper = require('../md5-wrapper');
var Constants = require('../util/constants');
var bufferSize = Constants.BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES;
 
var EventEmitter = require('events').EventEmitter;
 
/**
*  File read stream
*  1. Calculate md5
*  2. Track reading offset
*  3. Work with customize memory allocator
*  4. Buffer data from stream.
*  @param {object} options stream.Readable options
*/
function FileReadStream(path, options) {
  stream.Stream.call(this);
  this.readable = true;
 
  if(!options) {
    options = {};
  }
 
  this._destroyed = false;
  this._streamEnded = false;
  this._fd = null;
  this._fileName = undefined;
  this._highWaterMark = options.highWaterMark || bufferSize;
  this._offset = 0;
  this._paused = undefined;
  this._allocator = options.allocator;
  this._fileName = path;
 
  this._md5hash = null;
  this._md5sum = undefined;
 
  if (options.calcContentMd5) {
    this._md5hash = new Md5Wrapper().createMd5Hash();
  }
 
  this._open();
}
 
util.inherits(FileReadStream, stream.Stream);
 
/**
* Open file
*/
FileReadStream.prototype._open = function () {
  var flags = 'r';
  var self = this;
  fs.open(this._fileName, flags, function(error, fd) {
    if (error) {
      self.emit('error', error);
    } else {
      self._fd = fd;
      self.emit('open', fd);
    }
  });
};
 
/**
* Add event listener
*/
FileReadStream.prototype.on = function(event, listener) {
  if (event === 'data' && this._paused === undefined) {
    this._paused = false;
    this._emitData();
  }
 
  return EventEmitter.prototype.on.call(this, event, listener);
};
 
/**
* Get buffer
*/
FileReadStream.prototype._getBuffer = function(size) {
  if(this._allocator && this._allocator.getBuffer) {
    return this._allocator.getBuffer(size);
  } else {
    var buffer = new Buffer(size);
    return buffer;
  }
};
 
/**
* Release buffer
*/
FileReadStream.prototype._releaseBuffer = function(buffer) {
  if(this._allocator && this._allocator.releaseBuffer) {
    this._allocator.releaseBuffer(buffer);
  }
};
 
/**
* Emit the data from file
*/
FileReadStream.prototype._emitData = function() {
  var self = this;
  if(!this._fd) {
    this.once('open', function() {
      self._emitData();
    });
    return;
  }
 
  if (this._paused || this._streamEnded) {
    return;
  }
  var buffer = this._getBuffer(this._highWaterMark);
  fs.read(this._fd, buffer, 0, this._highWaterMark, this._offset, function(error, bytesRead, readBuffer) {
    if (error) {
      self.emit('error', error);
      return;
    }
 
    if(bytesRead === 0) {
      if(!self._streamEnded) {
        self._streamEnded = true;
        self.emit('end');
      }
      return;
    }
 
    var range = {
      start : self._offset,
      end : self._offset + bytesRead - 1,
      size : bytesRead
    };
 
    var data;
    if(bytesRead == self._highWaterMark) {
      data = readBuffer;
    } else {
      data = readBuffer.slice(0, bytesRead);
      //Release the current buffer since we created a new one
      self._releaseBuffer(readBuffer);
    }
 
    if(self._md5hash) {
      self._md5hash.update(data);
    }
 
    self.emit('data', data, range);
 
    // cleanup
    self._offset += bytesRead;
    buffer = readBuffer = data = null;
    self._emitData();
  });
};
 
/**
* Get file content md5 when read completely.
*/
FileReadStream.prototype.getContentMd5 = function(encoding) {
  if (!encoding) encoding = 'base64';
  if(!this._md5hash) {
    throw new Error('Can\'t get content md5, please set the calcContentMd5 option for FileReadStream.');
  } else {
    if (this._streamEnded) {
      if (!this._md5sum) {
        this._md5sum = this._md5hash.digest(encoding);
      }
      return this._md5sum;
    } else {
      throw new Error('FileReadStream has not ended.');
    }
  }
};
 
/**
* Pause chunk stream
*/
FileReadStream.prototype.pause = function() {
  this._paused = true;
};
 
/**
* Resume read stream
*/
FileReadStream.prototype.resume = function() {
  var previousState = this._paused;
  if (this._paused) {
    this._paused = false;
 
    if(previousState === true) {
      //Only start to emit data when it's in pause state
      this._emitData();
    }
  }
};
 
FileReadStream.prototype.finish = function () {
  this.destroy();
};
 
FileReadStream.prototype.destroy = function () {
  if (this._destroyed) {
    return;
  }
 
  var self = this;
  this.readable = false;
 
  function close(fd) {
    fs.close(fd || self._fd, function(err) {
      if (err) {
        self.emit('error', err);
      }
      else {
        self.emit('close');
      }
    });
    self._fd = null;
    self._destroyed = true;
  }
 
  // when the stream is closed immediately after creating it
  if (!validator.isInt(this._fd)) {
    this.once('open', close);
    return;
  }
 
  close();
};
 
module.exports = FileReadStream;
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/streams/rangestream.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/streams/rangestream.js

Statements: 10.74% (16 / 149)      Branches: 0% (0 / 53)      Functions: 0% (0 / 15)      Lines: 10.96% (16 / 146)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282                                1 1 1 1         1                                                                     1                                                                                                                               1                                                                                       1               1                     1                                                 1                                                   1                                         1             1             1             1    
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var azureCommon = require('./../common');
var azureutil = azureCommon.util;
var Constants = require('./../util/constants');
var EventEmitter = require('events').EventEmitter;
 
/**
* Range stream
*/
function RangeStream(serviceClient, container, blob, options) {
  this.serviceClient = serviceClient;
  this._emitter = new EventEmitter();
  this._paused = false;
  this._emittedAll = false;
  this._emittedRangeIndex = 0;
  this._rangelist = [];
  this._resourcePath = [];
  this._isEmitting = false;
  this._rangeStreamEnded = false;
  this._lengthHeader = Constants.HeaderConstants.CONTENT_LENGTH;
  this._minRangeSize = Constants.BlobConstants.MIN_WRITE_PAGE_SIZE_IN_BYTES;
  this._maxRangeSize = Constants.BlobConstants.DEFAULT_WRITE_PAGE_SIZE_IN_BYTES;
  if (options.rangeStart) {
    this._startOffset = options.rangeStart;
  } else {
    this._startOffset = 0;
  }
  this._dataOffset = this._startOffset;
  if (options.rangeEnd) {
    this._endOffset = options.rangeEnd;
  } else {
    this._endOffset = Number.MAX_VALUE;
  }
  if (container) {
    this._resourcePath.push(container);
  }
  if (blob) {
    this._resourcePath.push(blob); 
  }
}
 
/**
* Get range list
*/
RangeStream.prototype.list = function (options, callback) {
  var start = this._startOffset;
  var end;
  var singleRangeSize = Constants.BlobConstants.MAX_SINGLE_GET_PAGE_RANGE_SIZE;
 
  if (this._listFunc === undefined) {
    // the default function puts the whole blob into a single list item
    this._listFunc = this._defaultListFunc;
    end = this._endOffset;
  } else {
    end = Math.min(this._startOffset + singleRangeSize - 1, this._endOffset);
  }
  options.rangeStart = start;
  if (end != Number.MAX_VALUE) {
    options.rangeEnd = end;
  }
 
  var self = this;
  var onList = function (error, ranges, response) {
    if (error) {
      callback(error);
    } else {
      var totalSize = parseInt(response.headers[self._lengthHeader], 10);
      var endOffset = Math.min(totalSize - 1, self._endOffset);
      var rangeEnd = Math.min(end, endOffset);
  
      if (!ranges.length) {
        // convert single object to range
        // start >= end means there is no valid regions
        ranges.push({ start : start, end : rangeEnd, dataSize: 0 });
      } else if (ranges[ranges.length - 1].end !== rangeEnd) {
        // don't forget the zero chunk at the end of range
        ranges.push({ start : ranges[ranges.length - 1].end + 1, end : rangeEnd, dataSize: 0 });
      }
      
      if (end >= endOffset) {
        self._rangeStreamEnded = true;
      }
      self.resizeAndSaveRanges(ranges);
      self._startOffset += singleRangeSize;
      self._emitRange();
      
      // This is only valid when listing pages because when listing with the default function, the "endOffset" will always equal to or greater than the "end". 
      if (end < endOffset) {
        process.nextTick(function () {
          ranges = null;
          self.list(options, callback);
          self = null;
        });
      }
    }
  };
 
  var callArguments = Array.prototype.slice.call(this._resourcePath);
  callArguments.push(options);
  callArguments.push(onList);
  this._listFunc.apply(this.serviceClient, callArguments);
};
 
/**
* Resize regions:
*   1. Merge small pieces into a range no less than this._minRangeSize
*   2. Split large pieces into ranges no more than this._maxRangeSize
*/
RangeStream.prototype.resizeAndSaveRanges = function (ranges) {
  var rangeList = this._rangelist;
  var holdingRange = { type : 'range', size : 0, dataSize : 0, start : this._startOffset, end : -1 };
  var readingRange = null;
  var rangeSize = 0;
 
  for (var index = 0; index < ranges.length; index++) {
    readingRange = ranges[index];
    rangeSize = readingRange.end - holdingRange.start + 1;
    
    if (rangeSize < this._minRangeSize) {
      // merge fragment ranges
      this.mergeRanges(holdingRange, readingRange);
    } else {
      if (holdingRange.end != -1) {
        // save the holding range list and hold the reading range
        this.splitAndSaveRanges(holdingRange, rangeList);
        holdingRange = readingRange;
      }
      
      if (this._dataOffset != readingRange.start) {
        // padding zero for empty range and hold the reading range 
        this.putZeroRange(this._dataOffset, readingRange.start - 1, rangeList);
        holdingRange = readingRange;
      } else if (holdingRange.end == -1) {
        // if holdingRange is never set, it means readingRange exceeds MIN_WRITE_FILE_SIZE_IN_BYTES
        this.splitAndSaveRanges(readingRange, rangeList);
        // reading range has been saved, offset the holding start position for calculating the range size in next loop
        holdingRange.start = readingRange.end + 1;
      }
    }
    
    // If it is the last range, put the holding range into list anyway
    if (index == ranges.length - 1 && holdingRange.end > holdingRange.start) {
      this.splitAndSaveRanges(holdingRange, rangeList);
    }
    
    this._dataOffset = readingRange.end + 1;
  }
};
 
/**
* Put a zero range into range list
*/
RangeStream.prototype.putZeroRange = function (startOffset, endOffset, rangeList) {
  var zeroDataRange = { type : 'range', size : -1, dataSize : 0, start : startOffset, end : endOffset };
  this.splitAndSaveRanges(zeroDataRange, rangeList);
};
 
/**
* Merge small ranges
*/
RangeStream.prototype.mergeRanges = function (holdingRange, readingRange) {
  holdingRange.size = readingRange.end - holdingRange.start + 1;
  holdingRange.dataSize += readingRange.dataSize;
  holdingRange.end = readingRange.end;
  return holdingRange;
};
 
/**
* Split range into small pieces with maximum _maxRangeSize and minimum _minRangeSize size.
* For example, [0, 10G - 1] => [0, 4MB - 1], [4MB, 8MB - 1] ... [10GB - 4MB, 10GB - 1]
*/
RangeStream.prototype.splitAndSaveRanges = function (range, rangeList) {
  var rangeSize = range.end - range.start + 1;
  var offset = range.start;
  var limitedSize = 0;
 
  while (rangeSize > 0) {
    var newRange = { type : 'range', size : 0, dataSize : 0, start : -1, end : -1 };
    limitedSize = Math.min(rangeSize, this._maxRangeSize);
    newRange.start = offset;
    newRange.size = limitedSize;
    if (range.dataSize === 0) {
      newRange.dataSize = 0;
    } else {
      newRange.dataSize = limitedSize;
    }
    offset += limitedSize;
    newRange.end = offset - 1;
    rangeList.push(newRange);
    rangeSize -= limitedSize;
  }
};
 
/**
* Emit a range
*/
RangeStream.prototype._emitRange = function () {
  if (this._paused || this._emittedAll || this._isEmitting) return;
  this._isEmitting = true;
  try {
    for (; this._emittedRangeIndex < this._rangelist.length; this._emittedRangeIndex++) {
      if (this._paused) {
        return;
      }
      var range = this._rangelist[this._emittedRangeIndex];
      this._emitter.emit('range', range);
      this._rangelist[this._emittedRangeIndex] = null;
    }
    
    if (this._rangeStreamEnded) {
      this._rangelist = null;
      this._emittedAll = true;
      this._emitter.emit('end');
    }
  } finally {
    this._isEmitting = false;
  }
};
 
/**
* The Default list function which puts the whole blob into one range.
*/
RangeStream.prototype._defaultListFunc = function (container, blob, optionsOrCallback, callback) {
  var options;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; });
  
  this.getBlobProperties(container, blob, options, function (error, result, response) {
    if (error) {
      callback(error);
    } else {
      var range = [{}];
      range[0].start = options.rangeStart ? Math.max(options.rangeStart, 0) : 0;
      range[0].end = options.rangeEnd ? Math.min(options.rangeEnd, result.contentLength - 1) : result.contentLength - 1;
      range[0].size = range[0].end - range[0].start + 1;
      range[0].dataSize = range[0].size;
      callback(error, range, response);
    }
  });
};
 
/**
* Add event listener
*/
RangeStream.prototype.on = function (event, listener) {
  this._emitter.on(event, listener);
};
 
/**
* Pause the stream
*/
RangeStream.prototype.pause = function () {
  this._paused = true;
};
 
/**
* Resume the stream
*/
RangeStream.prototype.resume = function () {
  this._paused = false;
  if (!this._isEmitting) {
    this._emitRange();
  }
};
 
module.exports = RangeStream;
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/streams/readablefs.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/streams/readablefs.js

Statements: 42.86% (3 / 7)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 42.86% (3 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33                                1 1               1              
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var rs = require('readable-stream').Readable;
var fs = require('fs');
 
/*
* As far as streams support goes, we can get the node 0.10 stream API in node 0.8. 
* Use the readable-stream module (https://www.npmjs.org/package/readable-stream) which is 
* essentially a copy of the stream modules from core node 0.10 and it just works on both 0.8 and 0.10. 
*/
 
exports.createReadStream = function(path, options) {
  var stream = fs.createReadStream(path, options);
  if (/^v0\.8\./.test(process.version)) {
    stream = rs().wrap(stream);
  }
  return stream;
};
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/streams/speedsummary.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/streams/speedsummary.js

Statements: 16% (16 / 100)      Branches: 0% (0 / 41)      Functions: 0% (0 / 14)      Lines: 16.33% (16 / 98)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207                                1 1         1                             1                         1                                   1                                   1               1                   1                           1                                 1                 1                                             1                                   1                     1               1    
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var util = require('util');
var azureutil = require('../util/util');
 
/**
* Blob upload/download speed summary
*/
function SpeedSummary (name) {
  this.name = name;
  this._startTime = Date.now();
  this._timeWindowInSeconds = 10;
  this._timeWindow = this._timeWindowInSeconds * 1000;
  this._totalWindowSize = 0;
  this._speedTracks = new Array(this._timeWindowInSeconds);
  this._speedTrackPtr = 0;
  this.totalSize = undefined;
  this.completeSize = 0;
}
 
/**
* Convert the size to human readable size
*/
function toHumanReadableSize(size, len) {
  if(!size) return '0B';
  if (!len || len <= 0) {
    len = 2;
  }
  var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  var i = Math.floor( Math.log(size) / Math.log(1024));
  return (size/Math.pow(1024, i)).toFixed(len) + units[i];
}
 
/**
* Get running seconds
*/
SpeedSummary.prototype.getElapsedSeconds = function(humanReadable) {
  var now = Date.now();
  var seconds = parseInt((now - this._startTime) / 1000, 10);
  if (humanReadable !== false) {
    var s = parseInt(seconds % 60, 10);
    seconds /= 60;
    var m = Math.floor(seconds % 60);
    seconds /= 60;
    var h = Math.floor(seconds);
    seconds = util.format('%s:%s:%s', azureutil.zeroPaddingString(h, 2), azureutil.zeroPaddingString(m, 2), azureutil.zeroPaddingString(s, 2));
  }
  return seconds;
};
 
/**
* Get complete percentage
* @param {int} len The number of digits after the decimal point.
*/
SpeedSummary.prototype.getCompletePercent = function(len) {
  if (this.totalSize) {
    if(!len || len <= 0) {
      len = 1;
    }
    return (this.completeSize * 100 / this.totalSize).toFixed(len);
  } else {
    if(this.totalSize === 0) {
      return 100;
    } else {
      return 0;
    }
  }
};
 
/**
* Get average upload/download speed
*/
SpeedSummary.prototype.getAverageSpeed = function(humanReadable) {
  var elapsedTime = this.getElapsedSeconds(false);
  return this._getInternalSpeed(this.completeSize, elapsedTime, humanReadable);
};
 
/**
* Get instant speed
*/
SpeedSummary.prototype.getSpeed = function(humanReadable) {
  this._refreshSpeedTracks();
  var elapsedTime = this.getElapsedSeconds(false);
  elapsedTime = Math.min(elapsedTime, this._timeWindowInSeconds);
  return this._getInternalSpeed(this._totalWindowSize, elapsedTime, humanReadable);
};
 
/**
* Get internal speed
*/
SpeedSummary.prototype._getInternalSpeed = function(totalSize, elapsedTime, humanReadable) {
  if (elapsedTime <= 0) {
    elapsedTime = 1;
  }
  var speed = totalSize / elapsedTime;
  if(humanReadable !== false) {
    speed = toHumanReadableSize(speed) + '/s';
  }
  return speed;
};
 
/**
* Refresh speed tracks
*/
SpeedSummary.prototype._refreshSpeedTracks = function() {
  var now = Date.now();
  var totalSize = 0;
  for(var i = 0; i < this._speedTracks.length; i++) {
    if(!this._speedTracks[i]) continue;
    if(now - this._speedTracks[i].timeStamp <= this._timeWindow) {
      totalSize += this._speedTracks[i].size;
    } else {
      this._speedTracks[i] = null;
    }
  }
  this._totalWindowSize = totalSize;
};
 
/**
* Increment the complete data size
*/
SpeedSummary.prototype.increment = function(len) {
  this.completeSize += len;
  this._recordSpeed(len);
  return this.completeSize;
};
 
/**
* record complete size into speed tracks
*/
SpeedSummary.prototype._recordSpeed = function(completeSize) {
  var now = Date.now();
  var track = this._speedTracks[this._speedTrackPtr];
  if(track) {
    var timeDiff = now - track.timeStamp;
    if(timeDiff > this._timeWindow) {
      track.timeStamp = now;
      track.size = completeSize;
    } else if(timeDiff <= 1000) { //1 seconds
      track.size += completeSize;
    } else {
      this._speedTrackPtr = (this._speedTrackPtr + 1) % this._timeWindowInSeconds;
      this._recordSpeed(completeSize);
    }
  } else {
    track = {timeStamp : now, size: completeSize};
    this._speedTracks[this._speedTrackPtr] = track;
  }
};
 
/**
* Get auto increment function
*/
SpeedSummary.prototype.getAutoIncrementFunction = function(size) {
  var self = this;
  return function(error, retValue) {
    if(!error) {
      var doneSize = 0;
      if((!retValue && retValue !== 0) || isNaN(retValue)) {
        doneSize = size;
      } else {
        doneSize = retValue;
      }
      self.increment(doneSize);
    }
  };
};
 
/**
* Get total size
*/
SpeedSummary.prototype.getTotalSize = function(humanReadable) {
  if (humanReadable !== false) {
    return toHumanReadableSize(this.totalSize);
  } else {
    return this.totalSize;
  }
};
 
/**
* Get completed data size
*/
SpeedSummary.prototype.getCompleteSize = function(humanReadable) {
  if (humanReadable !== false) {
    return toHumanReadableSize(this.completeSize);
  } else {
    return this.completeSize;
  }
};
 
module.exports = SpeedSummary;
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/util/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/util/

Statements: 22.29% (115 / 516)      Branches: 1.26% (3 / 239)      Functions: 0.96% (1 / 104)      Lines: 22.37% (115 / 514)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/lib/common/util/
File Statements Branches Functions Lines
accesscondition.js 28.21% (11 / 39) 100% (0 / 0) 0% (0 / 10) 28.21% (11 / 39)
constants.js 100% (4 / 4) 100% (2 / 2) 100% (0 / 0) 100% (4 / 4)
date.js 25% (4 / 16) 100% (0 / 0) 0% (0 / 4) 25% (4 / 16)
iso8061date.js 16.67% (3 / 18) 0% (0 / 2) 0% (0 / 3) 16.67% (3 / 18)
patch-xmlbuilder.js 28.57% (2 / 7) 0% (0 / 2) 0% (0 / 1) 28.57% (2 / 7)
sr.js 100% (3 / 3) 100% (0 / 0) 100% (0 / 0) 100% (3 / 3)
storageutilities.js 100% (2 / 2) 100% (0 / 0) 100% (0 / 0) 100% (2 / 2)
util.js 23.18% (51 / 220) 0.77% (1 / 130) 2.38% (1 / 42) 23.39% (51 / 218)
validate.js 16.91% (35 / 207) 0% (0 / 103) 0% (0 / 44) 16.91% (35 / 207)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/util/accesscondition.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/util/accesscondition.js

Statements: 28.21% (11 / 39)      Branches: 100% (0 / 0)      Functions: 0% (0 / 10)      Lines: 28.21% (11 / 39)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167                                                  1             1                     1                         1                             1                             1                             1                             1                             1                             1                             1          
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Expose 'AccessCondition'.
 
/**
* Defines constants, enums, and utility functions for use with storage access condition.
* @namespace
*/
 
'use strict';
 
exports = module.exports;
 
/**
* Constructs an empty access condition.
*
* @return {object} An empty AccessCondition object
*/
exports.generateEmptyCondition = function () {
  return {};
};
 
/**
* Constructs an access condition such that an operation will be performed only if the resource does not exist on the service
*
* Setting this access condition modifies the request to include the HTTP If-None-Match conditional header
 
* @return {AccessConditions} An AccessCondition object that represents a condition that checks for nonexistence
*/
exports.generateIfNotExistsCondition = function () {
  var accessCondition = {};
  accessCondition.EtagNonMatch = '*';
  return accessCondition;
};
 
/**
* Constructs an access condition such that an operation will be performed only if the resource exists on the service
*
* Setting this access condition modifies the request to include the HTTP If-Match conditional header
 
* @return {AccessConditions} An AccessCondition object that represents a condition that checks for existence
*/
exports.generateIfExistsCondition = function () {
  var accessCondition = {};
  accessCondition.EtagMatch = '*';
  return accessCondition;
};
 
/**
* Constructs an access condition such that an operation will be performed only if the resource's ETag value 
* does not match the specified ETag value
*
* Setting this access condition modifies the request to include the HTTP If-None-Match conditional header
*
* @param  {string} etag                    The ETag value to check against the resource's ETag
* @return {AccessConditions}               An AccessCondition object that represents the If-None-Match condition
*/
exports.generateIfNoneMatchCondition = function (etag) {
  var accessCondition = {};
  accessCondition.EtagNonMatch = etag;
  return accessCondition;
};
 
/**
* Constructs an access condition such that an operation will be performed only if the resource's ETag value
* matches the specified ETag value
*
* Setting this access condition modifies the request to include the HTTP If-Match conditional header
*
* @param  {string} etag                    The ETag value to check against the resource's ETag
* @return {AccessConditions}               An AccessCondition object that represents the If-Match condition
*/
exports.generateIfMatchCondition = function (etag) {
  var accessCondition = {};
  accessCondition.EtagMatch = etag;
  return accessCondition;
};
 
/**
* Constructs an access condition such that an operation will be performed only if the resource has been
* modified since the specified time
*
* Setting this access condition modifies the request to include the HTTP If-Modified-Since conditional header
*
* @param  {Date|string}  time              A date object specifying the time since which the resource must have been modified
* @return {AccessConditions}               An AccessCondition object that represents the If-Modified-Since condition
*/
exports.generateIfModifiedSinceCondition = function (time) {
  var accessCondition = {};
  accessCondition.DateModifedSince = time;
  return accessCondition;
};
 
/**
* Constructs an access condition such that an operation will be performed only if the resource has not been
* modified since the specified time
*
* Setting this access condition modifies the request to include the HTTP If-Unmodified-Since conditional header
*
* @param  {Date|string}    time            A date object specifying the time since which the resource must have not been modified
* @return {AccessConditions}               An AccessCondition object that represents the If-Unmodified-Since condition
*/
exports.generateIfNotModifiedSinceCondition = function (time) {
  var accessCondition = {};
  accessCondition.DateUnModifiedSince = time;
  return accessCondition;
};
 
/**
* Constructs an access condition such that an operation will be performed only if the resource's sequence number
* is equal to the specified value
*
* Setting this access condition modifies the request to include the HTTP x-ms-if-sequence-number-eq conditional header
*
* @param  {Number|string}    sequenceNumber    A date object specifying the time since which the resource must have not been modified
* @return {AccessConditions}                   An AccessCondition object that represents the If-Unmodified-Since condition
*/
exports.generateSequenceNumberEqualCondition = function (sequenceNumber) {
  var accessCondition = {};
  accessCondition.SequenceNumberEqual = sequenceNumber;
  return accessCondition;
};
 
/**
* Constructs an access condition such that an operation will be performed only if the resource's sequence number
* is less than the specified value
*
* Setting this access condition modifies the request to include the HTTP x-ms-if-sequence-number-lt conditional header
*
* @param  {Number|string}    sequenceNumber    A date object specifying the time since which the resource must have not been modified
* @return {AccessConditions}                   An AccessCondition object that represents the If-Unmodified-Since condition
*/
exports.generateSequenceNumberLessThanCondition = function (sequenceNumber) {
  var accessCondition = {};
  accessCondition.SequenceNumberLessThan = sequenceNumber;
  return accessCondition;
};
 
/**
* Constructs an access condition such that an operation will be performed only if the resource's sequence number
* is less than or equal to the specified value
*
* Setting this access condition modifies the request to include the HTTP x-ms-if-sequence-number-le conditional header
*
* @param  {Number|string}    sequenceNumber    A date object specifying the time since which the resource must have not been modified
* @return {AccessConditions}                   An AccessCondition object that represents the If-Unmodified-Since condition
*/
exports.generateSequenceNumberLessThanOrEqualCondition = function (sequenceNumber) {
  var accessCondition = {};
  accessCondition.SequenceNumberLessThanOrEqual = sequenceNumber;
  return accessCondition;
};
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/util/constants.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/util/constants.js

Statements: 100% (4 / 4)      Branches: 100% (2 / 2)      Functions: 100% (0 / 0)      Lines: 100% (4 / 4)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395                                  1   1         1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1    
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Expose 'Constants'.
exports = module.exports;
 
var storageDnsSuffix = process.env.AZURE_STORAGE_DNS_SUFFIX || 'core.windows.net';
 
/**
* Defines constants.
*/
var Constants = {
  /*
  * Specifies the value to use for UserAgent header.
  */
  USER_AGENT_PRODUCT_NAME: 'Azure-Storage',
 
  /*
  * Specifies the value to use for UserAgent header.
  */
  USER_AGENT_PRODUCT_VERSION: '2.1.0',
 
  /**
  * The number of default concurrent requests for parallel operation.
  *
  * @const
  * @type {string}
  */
  DEFAULT_PARALLEL_OPERATION_THREAD_COUNT: 5,
 
  /**
  * Constant representing a kilobyte (Non-SI version).
  *
  * @const
  * @type {string}
  */
  KB: 1024,
 
  /**
  * Constant representing a megabyte (Non-SI version).
  *
  * @const
  * @type {string}
  */
  MB: 1024 * 1024,
 
  /**
  * Constant representing a gigabyte (Non-SI version).
  *
  * @const
  * @type {string}
  */
  GB: 1024 * 1024 * 1024,
 
  /**
  * Specifies HTTP.
  *
  * @const
  * @type {string}
  */
  HTTP: 'http:',
 
  /**
  * Specifies HTTPS.
  *
  * @const
  * @type {string}
  */
  HTTPS: 'https:',
  
  /**
  * Default HTTP port.
  *
  * @const
  * @type {int}
  */
  DEFAULT_HTTP_PORT: 80,
  
  /**
  * Default HTTPS port.
  *
  * @const
  * @type {int}
  */
  DEFAULT_HTTPS_PORT: 443,
 
  /**
   * Default client request timeout in milliseconds.
   * Integer containing the number of milliseconds to wait for a server to send response headers (and start the response body) before aborting the request.
   * 2 minutes by default.
   * 
   * @constant
   * @type {int}
   */
  DEFAULT_CLIENT_REQUEST_TIMEOUT_IN_MS: 120000,
 
  /**
  * Marker for atom metadata.
  *
  * @const
  * @type {string}
  */
  XML_METADATA_MARKER: '$',
 
  /**
  * Marker for atom value.
  *
  * @const
  * @type {string}
  */
  XML_VALUE_MARKER: '_',
  
  /**
  * Defines the service types indicators.
  * 
  * @const
  * @enum
  */
  ServiceType: {
    Blob: 'blob',
    Queue: 'queue',
    Table: 'table',
    File: 'file',
  },
 
  /**
  * Specifies the location used to indicate which location the operation can be performed against.
  *
  * @const
  * @enum
  */
  RequestLocationMode: {
    PRIMARY_ONLY: 0,
    SECONDARY_ONLY: 1,
    PRIMARY_OR_SECONDARY: 2,
  },
 
  /**
  * Represents a storage service location.
  *
  * @const
  * @enum
  */
  StorageLocation: {
    PRIMARY: 0,
    SECONDARY: 1,
  },
  
  AccountSasConstants:{
    /**
    * Permission types
    *
    * @const
    * @enum {string}
    */
    Permissions: {
      READ: 'r',
      ADD: 'a',
      CREATE: 'c',
      UPDATE: 'u',
      PROCESS: 'p',
      WRITE: 'w',
      DELETE: 'd',
      LIST: 'l'
    },
    
    /**
    * Services types
    *
    * @const
    * @enum {string}
    */
    Services: {
      BLOB: 'b',
      FILE: 'f',
      QUEUE: 'q',
      TABLE: 't',
    },
    
    /**
    * Resources types
    *
    * @const
    * @enum {string}
    */
    Resources: {
      SERVICE: 's',
      CONTAINER: 'c',
      OBJECT: 'o'
    },
    
    Protocols: {
      HTTPSONLY: 'https',
      HTTPSORHTTP: 'https,http'
    },
  },
 
  /**
  * Defines constants for use with shared access policies.
  */
  AclConstants: {
    /**
    * XML element for an access policy.
    *
    * @const
    * @type {string}
    */
    ACCESS_POLICY: 'AccessPolicy',
 
    /**
    * XML element for the end time of an access policy.
    *
    * @const
    * @type {string}
    */
    EXPIRY: 'Expiry',
 
    /**
    * XML attribute for IDs.
    *
    * @const
    * @type {string}
    */
    ID: 'Id',
 
    /**
    * XML element for the permission of an access policy.
    *
    * @const
    * @type {string}
    */
    PERMISSION: 'Permission',
 
    /**
    * XML element for a signed identifier.
    *
    * @const
    * @type {string}
    */
    SIGNED_IDENTIFIER_ELEMENT: 'SignedIdentifier',
 
    /**
    * XML element for signed identifiers.
    *
    * @const
    * @type {string}
    */
    SIGNED_IDENTIFIERS_ELEMENT: 'SignedIdentifiers',
 
    /**
    * XML element for the start time of an access policy.
    *
    * @const
    * @type {string}
    */
    START: 'Start'
  },
 
  /**
  * Defines constants for use with service properties.
  */
  ServicePropertiesConstants: {
    /**
    * XML element for storage service properties.
    *
    * @const
    * @type {string}
    */
    STORAGE_SERVICE_PROPERTIES_ELEMENT: 'StorageServiceProperties',
 
    /**
    * Default analytics version to send for logging, hour metrics and minute metrics.
    *
    * @const
    * @type {string}
    */
    DEFAULT_ANALYTICS_VERSION: '1.0',
 
    /**
    * XML element for logging.
    *
    * @const
    * @type {string}
    */
    LOGGING_ELEMENT: 'Logging',
 
    /**
    * XML element for version.
    *
    * @const
    * @type {string}
    */
    VERSION_ELEMENT: 'Version',
 
    /**
    * XML element for delete.
    *
    * @const
    * @type {string}
    */
    DELETE_ELEMENT: 'Delete',
 
    /**
    * XML element for read.
    *
    * @const
    * @type {string}
    */
    READ_ELEMENT: 'Read',
 
    /**
    * XML element for write.
    *
    * @const
    * @type {string}
    */
    WRITE_ELEMENT: 'Write',
 
    /**
    * XML element for retention policy.
    *
    * @const
    * @type {string}
    */
    RETENTION_POLICY_ELEMENT: 'RetentionPolicy',
 
    /**
    * XML element for enabled.
    *
    * @const
    * @type {string}
    */
    ENABLED_ELEMENT: 'Enabled',
 
    /**
    * XML element for days.
    *
    * @const
    * @type {string}
    */
    DAYS_ELEMENT: 'Days',
 
    /**
    * XML element for HourMetrics.
    *
    * @const
    * @type {string}
    */
    HOUR_METRICS_ELEMENT: 'HourMetrics',
 
    /**
    * XML element for MinuteMetrics.
    *
    * @const
    * @type {string}
    */
    MINUTE_METRICS_ELEMENT: 'MinuteMetrics',
 
    /**
    * XML element for Cors.
    *
    * @const
    * @type {string}
    */
    CORS_ELEMENT: 'Cors',
 
    /**
    * XML element for CorsRule.
    *
    * @const
    * @type {string}
    */
    CORS_RULE_ELEMENT: 'CorsRule',
 
    /**
    * XML element for AllowedOrigins.
    *
    * @const
    * @type {string}
    */
    ALLOWED_ORIGINS_ELEMENT: 'AllowedOrigins',
 
    /**
    * XML element for AllowedMethods.
    *
    * @const
    * @type {string}
    */
    ALLOWED_METHODS_ELEMENT: 'AllowedMethods',
 
    /**
    * XML element for MaxAgeInSeconds.
    *
    * @const
    * @type {string}
    */
    MAX_AGE_IN_SECONDS_ELEMENT: 'MaxAgeInSeconds',
 
    /**
    * XML element for ExposedHeaders.
    *
    * @const
    * @type {string}
    */
    EXPOSED_HEADERS_ELEMENT: 'ExposedHeaders',
 
    /**
    * XML element for AllowedHeaders.
    *
    * @const
    * @type {string}
    */
    ALLOWED_HEADERS_ELEMENT: 'AllowedHeaders',
 
    /**
    * XML element for IncludeAPIs.
    *
    * @const
    * @type {string}
    */
    INCLUDE_APIS_ELEMENT: 'IncludeAPIs',
 
    /**
    * XML element for DefaultServiceVersion.
    *
    * @const
    * @type {string}
    */
    DEFAULT_SERVICE_VERSION_ELEMENT: 'DefaultServiceVersion'
  },
 
  /**
  * Defines constants for use with blob operations.
  */
  BlobConstants: {
    /**
    * XML element for the latest.
    *
    * @const
    * @type {string}
    */
    LATEST_ELEMENT: 'Latest',
 
    /**
    * XML element for uncommitted blocks.
    *
    * @const
    * @type {string}
    */
    UNCOMMITTED_ELEMENT: 'Uncommitted',
 
    /**
    * XML element for a block list.
    *
    * @const
    * @type {string}
    */
    BLOCK_LIST_ELEMENT: 'BlockList',
 
    /**
    * XML element for committed blocks.
    *
    * @const
    * @type {string}
    */
    COMMITTED_ELEMENT: 'Committed',
 
    /**
    * The default write page size, in bytes, used by blob streams.
    *
    * @const
    * @type {int}
    */
    DEFAULT_WRITE_PAGE_SIZE_IN_BYTES: 4 * 1024 * 1024,
    
    /**
    * The minimum write page size, in bytes, used by blob streams.
    *
    * @const
    * @type {int}
    */
    MIN_WRITE_PAGE_SIZE_IN_BYTES: 2 * 1024 * 1024,
 
    /**
    * The default maximum size, in bytes, of a blob before it must be separated into blocks.
    *
    * @const
    * @type {int}
    */
    DEFAULT_SINGLE_BLOB_PUT_THRESHOLD_IN_BYTES: 32 * 1024 * 1024,
 
    /**
    * The default write block size, in bytes, used by blob streams.
    *
    * @const
    * @type {int}
    */
    DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES: 4 * 1024 * 1024,
 
    /**
    * The maximum size of a single block of block blob.
    *
    * @const
    * @type {int}
    */
    MAX_BLOCK_BLOB_BLOCK_SIZE: 100 * 1024 * 1024,
 
    /**
    * The maximum size of a single block of append blob.
    *
    * @const
    * @type {int}
    */
    MAX_APPEND_BLOB_BLOCK_SIZE: 4 * 1024 * 1024,
 
    /**
    * The maximum size, in bytes, of a blob before it must be separated into blocks.
    *
    * @const
    * @type {int}
    */
    MAX_SINGLE_UPLOAD_BLOB_SIZE_IN_BYTES: 64 * 1024 * 1024,
 
    /**
    * The maximum range get size when requesting for a contentMD5
    */
    MAX_RANGE_GET_SIZE_WITH_MD5 : 4 * 1024 * 1024,
 
    /**
    * The maximum page range size for a page update operation.
    */
    MAX_UPDATE_PAGE_SIZE : 4 * 1024 * 1024,
    
    /**
    * The maximum buffer size for writing a stream buffer.
    */
    MAX_QUEUED_WRITE_DISK_BUFFER_SIZE : 64 * 1024 * 1024,
    
    /**
    * Max size for single get page range. The max value should be 150MB
    * http://blogs.msdn.com/b/windowsazurestorage/archive/2012/03/26/getting-the-page-ranges-of-a-large-page-blob-in-segments.aspx
    */
    MAX_SINGLE_GET_PAGE_RANGE_SIZE : 37 * 4 * 1024 * 1024,
 
    /**
    * The size of a page, in bytes, in a page blob.
    *
    * @const
    * @type {string}
    */
    PAGE_SIZE: 512,
 
    /**
    * Resource types.
    *
    * @const
    * @enum {string}
    */
    ResourceTypes: {
      CONTAINER: 'c',
      BLOB: 'b'
    },
 
    /**
    * List blob types.
    *
    * @const
    * @enum {string}
    */
    ListBlobTypes: {
      Blob: 'b',
      Directory: 'd'
    },
 
    /**
    * Put page write options
    *
    * @const
    * @enum {string}
    */
    PageWriteOptions: {
      UPDATE: 'update',
      CLEAR: 'clear'
    },
 
    /**
    * Blob types
    *
    * @const
    * @enum {string}
    */
    BlobTypes: {
      BLOCK: 'BlockBlob',
      PAGE: 'PageBlob',
      APPEND: 'AppendBlob'
    },
 
    /**
    * Blob lease constants
    *
    * @const
    * @enum {string}
    */
    LeaseOperation: {
      ACQUIRE: 'acquire',
      RENEW: 'renew',
      CHANGE: 'change',
      RELEASE: 'release',
      BREAK: 'break'
    }
  },
 
  /**
  * Defines constants for use with file operations.
  */
  FileConstants: {
    /**
    * The default write size, in bytes, used by file streams.
    *
    * @const
    * @type {string}
    */
    DEFAULT_WRITE_SIZE_IN_BYTES: 4 * 1024 * 1024,
 
    /**
    * The maximum range size when requesting for a contentMD5.
    */
    MAX_RANGE_GET_SIZE_WITH_MD5 : 4 * 1024 * 1024,
 
    /**
    * The maximum range size for a file update operation.
    */
    MAX_UPDATE_FILE_SIZE : 4 * 1024 * 1024,
 
    /**
    * The default minimum size, in bytes, of a file when it must be separated into ranges.
    *
    * @const
    * @type {int}
    */
    DEFAULT_SINGLE_FILE_GET_THRESHOLD_IN_BYTES: 32 * 1024 * 1024,
 
    /**
    * The minimum write file size, in bytes, used by file streams.
    *
    * @const
    * @type {int}
    */
    MIN_WRITE_FILE_SIZE_IN_BYTES: 2 * 1024 * 1024,
 
    /**
    * Put range write options
    *
    * @const
    * @enum {string}
    */
    RangeWriteOptions: {
      UPDATE: 'update',
      CLEAR: 'clear'
    },
 
    /**
    * Resource types.
    *
    * @const
    * @enum {string}
    */
    ResourceTypes: {
      SHARE: 's',
      FILE: 'f'
    }
  },
 
  /**
  * Defines constants for use with queue storage.
  *
  * @const
  * @type {string}
  */
  QueueConstants: {
    /**
    * XML element for QueueMessage.
    *
    * @const
    * @type {string}
    */
    QUEUE_MESSAGE_ELEMENT: 'QueueMessage',
 
    /**
    * XML element for MessageText.
    *
    * @const
    * @type {string}
    */
    MESSAGE_TEXT_ELEMENT: 'MessageText'
  },
 
  /**
  * Defines constants for use with table storage.
  *
  * @const
  * @type {string}
  */
  TableConstants: {
    /**
    * The changeset response delimiter.
    *
    * @const
    * @type {string}
    */
    CHANGESET_DELIMITER: '--changesetresponse_',
 
    /**
    * The batch response delimiter.
    *
    * @const
    * @type {string}
    */
    BATCH_DELIMITER: '--batchresponse_',
 
    /**
    * The next continuation row key token.
    *
    * @const
    * @type {string}
    */
    CONTINUATION_NEXT_ROW_KEY: 'x-ms-continuation-nextrowkey',
 
    /**
    * The next continuation partition key token.
    *
    * @const
    * @type {string}
    */
    CONTINUATION_NEXT_PARTITION_KEY: 'x-ms-continuation-nextpartitionkey',
 
    /**
    * The next continuation table name token.
    *
    * @const
    * @type {string}
    */
    CONTINUATION_NEXT_TABLE_NAME: 'x-ms-continuation-nexttablename',
 
    /**
    * The next row key query string argument.
    *
    * @const
    * @type {string}
    */
    NEXT_ROW_KEY: 'NextRowKey',
 
        /**
    * The next partition key query string argument.
    *
    * @const
    * @type {string}
    */
    NEXT_PARTITION_KEY: 'NextPartitionKey',
 
    /**
    * The next table name query string argument.
    *
    * @const
    * @type {string}
    */
    NEXT_TABLE_NAME: 'NextTableName',
 
    /** 
    * Prefix of the odata properties returned in a JSON query
    */
    ODATA_PREFIX: 'odata.',
 
    /**
    * Constant representing the string following a type annotation in a JSON table query
    */
    ODATA_TYPE_SUFFIX: '@odata.type',
 
    /**
    * Constant representing the property where the odata metadata elements are stored.
    *
    * @const
    * @type {string}
    */
    ODATA_METADATA_MARKER: '.metadata',
 
    /**
    * Constant representing the value for an entity property.
    */
    ODATA_VALUE_MARKER: '_',
 
    /** 
    * Constant representing the type for an entity property.
    */
    ODATA_TYPE_MARKER: '$',
 
    /**
    * The value to set the maximum data service version header.
    * @const
    * @type {string}
    */
    DEFAULT_DATA_SERVICE_VERSION: '3.0;NetFx',
 
    /**
    * The name of the property that stores the table name.
    *
    * @const
    * @type {string}
    */
    TABLE_NAME: 'TableName',
 
    /**
    * The name of the special table used to store tables.
    *
    * @const
    * @type {string}
    */
    TABLE_SERVICE_TABLE_NAME: 'Tables',
 
    /**
    * Operations
    *
    * @const
    * @enum {string}
    */
    Operations: {
      RETRIEVE: 'RETRIEVE',
      INSERT: 'INSERT',
      REPLACE: 'REPLACE',
      MERGE: 'MERGE',
      DELETE: 'DELETE',
      INSERT_OR_REPLACE: 'INSERT_OR_REPLACE',
      INSERT_OR_MERGE: 'INSERT_OR_MERGE'
    }
  },
 
  /**
  * Defines constants for use with HTTP headers.
  */
  HeaderConstants: {
    /**
    * The accept ranges header.
    *
    * @const
    * @type {string}
    */
    ACCEPT_RANGES: 'accept_ranges',
 
    /**
    * The content transfer encoding header.
    *
    * @const
    * @type {string}
    */
    CONTENT_TRANSFER_ENCODING: 'content-transfer-encoding',
 
    /**
    * The transfer encoding header.
    *
    * @const
    * @type {string}
    */
    TRANSFER_ENCODING: 'transfer-encoding',
 
    /**
    * The server header.
    *
    * @const
    * @type {string}
    */
    SERVER: 'server',
 
    /**
    * The location header.
    *
    * @const
    * @type {string}
    */
    LOCATION: 'location',
 
    /**
    * The Last-Modified header
    *
    * @const
    * @type {string}
    */
    LAST_MODIFIED: 'Last-Modified',
 
    /**
    * The data service version.
    *
    * @const
    * @type {string}
    */
    DATA_SERVICE_VERSION: 'dataserviceversion',
 
    /**
    * The maximum data service version.
    *
    * @const
    * @type {string}
    */
    MAX_DATA_SERVICE_VERSION: 'maxdataserviceversion',
 
    /**
    * The master Windows Azure Storage header prefix.
    *
    * @const
    * @type {string}
    */
    PREFIX_FOR_STORAGE: 'x-ms-',
 
    /**
    * The client request Id header.
    *
    * @const
    * @type {string}
    */
    CLIENT_REQUEST_ID: 'x-ms-client-request-id',
 
    /**
    * The header that specifies the approximate message count of a queue.
    *
    * @const
    * @type {string}
    */
    APPROXIMATE_MESSAGES_COUNT: 'x-ms-approximate-messages-count',
 
    /**
    * The Authorization header.
    *
    * @const
    * @type {string}
    */
    AUTHORIZATION: 'authorization',
 
    /**
    * The header that is used to avoid browser cache.
    *
    * @const
    * @type {string}
    */
    FORCE_NO_CACHE_IN_BROWSER: '_',
 
    /**
    * The header that specifies public access to blobs.
    *
    * @const
    * @type {string}
    */
    BLOB_PUBLIC_ACCESS: 'x-ms-blob-public-access',
 
    /**
    * The header for the blob type.
    *
    * @const
    * @type {string}
    */
    BLOB_TYPE: 'x-ms-blob-type',
 
    /**
    * The header for the type.
    *
    * @const
    * @type {string}
    */
    TYPE: 'x-ms-type',
 
    /**
    * Specifies the block blob type.
    *
    * @const
    * @type {string}
    */
    BLOCK_BLOB: 'blockblob',
 
    /**
    * The CacheControl header.
    *
    * @const
    * @type {string}
    */
    CACHE_CONTROL: 'cache-control',
 
    /**
    * The header that specifies blob caching control.
    *
    * @const
    * @type {string}
    */
    BLOB_CACHE_CONTROL: 'x-ms-blob-cache-control',
 
    /**
    * The header that specifies caching control.
    *
    * @const
    * @type {string}
    */
    FILE_CACHE_CONTROL: 'x-ms-cache-control',
 
    /**
    * The copy status.
    *
    * @const
    * @type {string}
    */
    COPY_STATUS: 'x-ms-copy-status',
 
    /**
    * The copy completion time
    *
    * @const
    * @type {string}
    */
    COPY_COMPLETION_TIME: 'x-ms-copy-completion-time',
 
    /**
    * The copy status message
    *
    * @const
    * @type {string}
    */
    COPY_STATUS_DESCRIPTION: 'x-ms-copy-status-description',
 
    /**
    * The copy identifier.
    *
    * @const
    * @type {string}
    */
    COPY_ID: 'x-ms-copy-id',
 
    /**
    * Progress of any copy operation
    *
    * @const
    * @type {string}
    */
    COPY_PROGRESS: 'x-ms-copy-progress',
 
    /**
    * The copy action.
    *
    * @const
    * @type {string}
    */
    COPY_ACTION: 'x-ms-copy-action',
 
    /**
    * Flag if the blob is incremental copy blob.
    */
    INCREMENTAL_COPY: 'x-ms-incremental-copy',
 
    /**
    * Snapshot time of the last successful incremental copy snapshot for this blob.
    */
    COPY_DESTINATION_SNAPSHOT: 'x-ms-copy-destination-snapshot',
 
    /**
    * The ContentID header.
    *
    * @const
    * @type {string}
    */
    CONTENT_ID: 'content-id',
 
    /**
    * The ContentEncoding header.
    *
    * @const
    * @type {string}
    */
    CONTENT_ENCODING: 'content-encoding',
 
    /**
    * The header that specifies blob content encoding.
    *
    * @const
    * @type {string}
    */
    BLOB_CONTENT_ENCODING: 'x-ms-blob-content-encoding',
 
    /**
    * The header that specifies content encoding.
    *
    * @const
    * @type {string}
    */
    FILE_CONTENT_ENCODING: 'x-ms-content-encoding',
 
    /**
    * The ContentLangauge header.
    *
    * @const
    * @type {string}
    */
    CONTENT_LANGUAGE: 'content-language',
 
    /**
    * The header that specifies blob content language.
    *
    * @const
    * @type {string}
    */
    BLOB_CONTENT_LANGUAGE: 'x-ms-blob-content-language',
 
    /**
    * The header that specifies content language.
    *
    * @const
    * @type {string}
    */
    FILE_CONTENT_LANGUAGE: 'x-ms-content-language',
 
    /**
    * The ContentLength header.
    *
    * @const
    * @type {string}
    */
    CONTENT_LENGTH: 'content-length',
 
    /**
    * The header that specifies blob content length.
    *
    * @const
    * @type {string}
    */
    BLOB_CONTENT_LENGTH: 'x-ms-blob-content-length',
 
    /**
    * The header that specifies content length.
    *
    * @const
    * @type {string}
    */
    FILE_CONTENT_LENGTH: 'x-ms-content-length',
 
    /**
    * The ContentDisposition header.
    * @const
    * @type {string}
    */
    CONTENT_DISPOSITION: 'content-disposition',
 
    /**
    * The header that specifies blob content disposition.
    *
    * @const
    * @type {string}
    */
    BLOB_CONTENT_DISPOSITION: 'x-ms-blob-content-disposition',
 
    /**
    * The header that specifies content disposition.
    *
    * @const
    * @type {string}
    */
    FILE_CONTENT_DISPOSITION: 'x-ms-content-disposition',
 
    /**
    * The ContentMD5 header.
    *
    * @const
    * @type {string}
    */
    CONTENT_MD5: 'content-md5',
 
    /**
    * The header that specifies blob content MD5.
    *
    * @const
    * @type {string}
    */
    BLOB_CONTENT_MD5: 'x-ms-blob-content-md5',
 
    /**
    * The header that specifies content MD5.
    *
    * @const
    * @type {string}
    */
    FILE_CONTENT_MD5: 'x-ms-content-md5',
 
    /**
    * The ContentRange header.
    *
    * @const
    * @type {string}
    */
    CONTENT_RANGE: 'cache-range',
 
    /**
    * The ContentType header.
    *
    * @const
    * @type {string}
    */
    CONTENT_TYPE: 'content-type',
 
    /**
    * The header that specifies blob content type.
    *
    * @const
    * @type {string}
    */
    BLOB_CONTENT_TYPE: 'x-ms-blob-content-type',
 
    /**
    * The header that specifies content type.
    *
    * @const
    * @type {string}
    */
    FILE_CONTENT_TYPE: 'x-ms-content-type',
 
    /**
    * The header for copy source.
    *
    * @const
    * @type {string}
    */
    COPY_SOURCE: 'x-ms-copy-source',
 
    /**
    * The header that specifies the date.
    *
    * @const
    * @type {string}
    */
    DATE: 'date',
 
    /**
    * The header that specifies the date.
    *
    * @const
    * @type {string}
    */
    MS_DATE: 'x-ms-date',
 
    /**
    * The header to delete snapshots.
    *
    * @const
    * @type {string}
    */
    DELETE_SNAPSHOT: 'x-ms-delete-snapshots',
 
    /**
    * The ETag header.
    *
    * @const
    * @type {string}
    */
    ETAG: 'etag',
 
    /**
    * The IfMatch header.
    *
    * @const
    * @type {string}
    */
    IF_MATCH: 'if-match',
 
    /**
    * The IfModifiedSince header.
    *
    * @const
    * @type {string}
    */
    IF_MODIFIED_SINCE: 'if-modified-since',
 
    /**
    * The IfNoneMatch header.
    *
    * @const
    * @type {string}
    */
    IF_NONE_MATCH: 'if-none-match',
 
    /**
    * The IfUnmodifiedSince header.
    *
    * @const
    * @type {string}
    */
    IF_UNMODIFIED_SINCE: 'if-unmodified-since',
 
    /**
    * Specifies snapshots are to be included.
    *
    * @const
    * @type {string}
    */
    INCLUDE_SNAPSHOTS_VALUE: 'include',
 
    /**
    * Specifies that the content-type is JSON.
    *
    * @const
    * @type {string}
    */
    JSON_CONTENT_TYPE_VALUE: 'application/json;',
 
 
    /**
    * The header that specifies lease ID.
    *
    * @const
    * @type {string}
    */
    LEASE_ID: 'x-ms-lease-id',
 
    /**
    * The header that specifies the lease break period.
    *
    * @const
    * @type {string}
    */
    LEASE_BREAK_PERIOD: 'x-ms-lease-break-period',
 
    /**
    * The header that specifies the proposed lease identifier.
    *
    * @const
    * @type {string}
    */
    PROPOSED_LEASE_ID: 'x-ms-proposed-lease-id',
 
    /**
    * The header that specifies the lease duration.
    *
    * @const
    * @type {string}
    */
    LEASE_DURATION: 'x-ms-lease-duration',
 
    /**
    * The header that specifies the source lease ID.
    *
    * @const
    * @type {string}
    */
    SOURCE_LEASE_ID: 'x-ms-source-lease-id',
 
    /**
    * The header that specifies lease time.
    *
    * @const
    * @type {string}
    */
    LEASE_TIME: 'x-ms-lease-time',
 
    /**
    * The header that specifies lease status.
    *
    * @const
    * @type {string}
    */
    LEASE_STATUS: 'x-ms-lease-status',
 
    /**
    * The header that specifies lease state.
    *
    * @const
    * @type {string}
    */
    LEASE_STATE: 'x-ms-lease-state',
 
    /**
    * Specifies the page blob type.
    *
    * @const
    * @type {string}
    */
    PAGE_BLOB: 'PageBlob',
 
    /**
    * The header that specifies page write mode.
    *
    * @const
    * @type {string}
    */
    PAGE_WRITE: 'x-ms-page-write',
 
    /**
    * The header that specifies file range write mode.
    *
    * @const
    * @type {string}
    */
    FILE_WRITE: 'x-ms-write',
 
    /**
    * The header that specifies whether the response should include the inserted entity.
    *
    * @const
    * @type {string}
    */
    PREFER: 'Prefer',
 
    /**
    * The header value which specifies that the response should include the inserted entity.
    *
    * @const
    * @type {string}
    */
    PREFER_CONTENT: 'return-content',
 
    /**
    * The header value which specifies that the response should not include the inserted entity.
    *
    * @const
    * @type {string}
    */
    PREFER_NO_CONTENT: 'return-no-content',
 
    /**
    * The header prefix for metadata.
    *
    * @const
    * @type {string}
    */
    PREFIX_FOR_STORAGE_METADATA: 'x-ms-meta-',
 
    /**
    * The header prefix for properties.
    *
    * @const
    * @type {string}
    */
    PREFIX_FOR_STORAGE_PROPERTIES: 'x-ms-prop-',
 
    /**
    * The Range header.
    *
    * @const
    * @type {string}
    */
    RANGE: 'Range',
 
    /**
    * The header that specifies if the request will populate the ContentMD5 header for range gets.
    *
    * @const
    * @type {string}
    */
    RANGE_GET_CONTENT_MD5: 'x-ms-range-get-content-md5',
 
    /**
    * The format string for specifying ranges.
    *
    * @const
    * @type {string}
    */
    RANGE_HEADER_FORMAT: 'bytes:%d-%d',
 
    /**
    * The header that indicates the request ID.
    *
    * @const
    * @type {string}
    */
    REQUEST_ID: 'x-ms-request-id',
 
    /**
    * The header for specifying the sequence number.
    *
    * @const
    * @type {string}
    */
    SEQUENCE_NUMBER: 'x-ms-blob-sequence-number',
 
    /**
    * The header for specifying the If-Sequence-Number-EQ condition.
    *
    * @const
    * @type {string}
    */
    SEQUENCE_NUMBER_EQUAL: 'x-ms-if-sequence-number-eq',
 
    /**
    * The header for specifying the If-Sequence-Number-LT condition.
    *
    * @const
    * @type {string}
    */
    SEQUENCE_NUMBER_LESS_THAN: 'x-ms-if-sequence-number-lt',
 
    /**
    * The header for specifying the If-Sequence-Number-LE condition.
    *
    * @const
    * @type {string}
    */
    SEQUENCE_NUMBER_LESS_THAN_OR_EQUAL: 'x-ms-if-sequence-number-le',
 
    /**
    * The header that specifies sequence number action.
    *
    * @const
    * @type {string}
    */
    SEQUENCE_NUMBER_ACTION: 'x-ms-sequence-number-action',
 
    /**
    * The header for the blob content length.
    *
    * @const
    * @type {string}
    */
    SIZE: 'x-ms-blob-content-length',
 
    /**
    * The header for snapshots.
    *
    * @const
    * @type {string}
    */
    SNAPSHOT: 'x-ms-snapshot',
 
    /**
    * Specifies only snapshots are to be included.
    *
    * @const
    * @type {string}
    */
    SNAPSHOTS_ONLY_VALUE: 'only',
 
    /**
    * The header for the If-Match condition.
    *
    * @const
    * @type {string}
    */
    SOURCE_IF_MATCH: 'x-ms-source-if-match',
 
    /**
    * The header for the If-Modified-Since condition.
    *
    * @const
    * @type {string}
    */
    SOURCE_IF_MODIFIED_SINCE: 'x-ms-source-if-modified-since',
 
    /**
    * The header for the If-None-Match condition.
    *
    * @const
    * @type {string}
    */
    SOURCE_IF_NONE_MATCH: 'x-ms-source-if-none-match',
 
    /**
    * The header for the If-Unmodified-Since condition.
    *
    * @const
    * @type {string}
    */
    SOURCE_IF_UNMODIFIED_SINCE: 'x-ms-source-if-unmodified-since',
 
    /**
    * The header for data ranges.
    *
    * @const
    * @type {string}
    */
    STORAGE_RANGE: 'x-ms-range',
 
    /**
    * The header for storage version.
    *
    * @const
    * @type {string}
    */
    STORAGE_VERSION: 'x-ms-version',
 
    /**
    * The current storage version header value.
    *
    * @const
    * @type {string}
    */
    TARGET_STORAGE_VERSION: '2016-05-31',
 
    /**
    * The UserAgent header.
    *
    * @const
    * @type {string}
    */
    USER_AGENT: 'user-agent',
 
    /**
    * The pop receipt header.
    *
    * @const
    * @type {string}
    */
    POP_RECEIPT: 'x-ms-popreceipt',
 
    /**
    * The time next visibile header.
    *
    * @const
    * @type {string}
    */
    TIME_NEXT_VISIBLE: 'x-ms-time-next-visible',
 
    /**
    * The approximate message counter header.
    *
    * @const
    * @type {string}
    */
    APPROXIMATE_MESSAGE_COUNT: 'x-ms-approximate-message-count',
 
    /**
    * The lease action header.
    *
    * @const
    * @type {string}
    */
    LEASE_ACTION: 'x-ms-lease-action',
 
    /**
    * The accept header.
    *
    * @const
    * @type {string}
    */
    ACCEPT: 'accept',
 
    /**
    * The accept charset header.
    *
    * @const
    * @type {string}
    */
    ACCEPT_CHARSET: 'Accept-Charset',
 
    /**
    * The host header.
    *
    * @const
    * @type {string}
    */
    HOST: 'host',
 
    /**
    * The correlation identifier header.
    *
    * @const
    * @type {string}
    */
    CORRELATION_ID: 'x-ms-correlation-id',
 
    /**
    * The group identifier header.
    *
    * @const
    * @type {string}
    */
    GROUP_ID: 'x-ms-group-id',
 
    /**
    * The share quota header.
    *
    * @const
    * @type {string}
    */
    SHARE_QUOTA: 'x-ms-share-quota',
    
    /**
    * The max blob size header.
    *
    * @const
    * @type {int}
    */
    BLOB_CONDITION_MAX_SIZE: 'x-ms-blob-condition-maxsize',
 
    /**
    * The append blob position header.
    *
    * @const
    * @type {int}
    */
    BLOB_CONDITION_APPEND_POSITION: 'x-ms-blob-condition-appendpos',
 
    /**
    * The append blob append offset header.
    *
    * @const
    * @type {int}
    */
    BLOB_APPEND_OFFSET: 'x-ms-blob-append-offset',
 
    /**
    * The append blob committed block header.
    *
    * @const
    * @type {int}
    */
    BLOB_COMMITTED_BLOCK_COUNT: 'x-ms-blob-committed-block-count',
 
    /**
    * If the data and application metadata are completely encrypted using the specified algorithm.
    *
    * @const
    * @type {bool}
    */
    SERVER_ENCRYPTED: 'x-ms-server-encrypted',
  },
 
  QueryStringConstants: {
 
    /**
    * Query component for SAS API version.
    * @const
    * @type {string}
    */
    API_VERSION: 'api-version',
 
    /**
    * The Comp value.
    *
    * @const
    * @type {string}
    */
    COMP: 'comp',
 
    /**
    * The Res Type.
    *
    * @const
    * @type {string}
    */
    RESTYPE: 'restype',
 
    /**
    * The copy Id.
    * @const
    * @type {string}
    */
    COPY_ID: 'copyid',
 
    /**
    * The Snapshot value.
    *
    * @const
    * @type {string}
    */
    SNAPSHOT: 'snapshot',
 
    /**
    * The previous snapshot value.
    *
    * @const
    * @type {string}
    */
    PREV_SNAPSHOT: 'prevsnapshot',
 
    /**
    * The timeout value.
    *
    * @const
    * @type {string}
    */
    TIMEOUT: 'timeout',
 
    /**
    * The signed start time query string argument for shared access signature.
    *
    * @const
    * @type {string}
    */
    SIGNED_START: 'st',
 
    /**
    * The signed expiry time query string argument for shared access signature.
    *
    * @const
    * @type {string}
    */
    SIGNED_EXPIRY: 'se',
 
    /**
    * The signed resource query string argument for shared access signature.
    *
    * @const
    * @type {string}
    */
    SIGNED_RESOURCE: 'sr',
 
    /**
    * The signed permissions query string argument for shared access signature.
    *
    * @const
    * @type {string}
    */
    SIGNED_PERMISSIONS: 'sp',
    
    /**
    * The signed services query string argument for shared access signature.
    *
    * @const
    * @type {string}
    */
    SIGNED_SERVICES: 'ss',
    
    /**
    * The signed resource types query string argument for shared access signature.
    *
    * @const
    * @type {string}
    */
    SIGNED_RESOURCE_TYPES: 'srt',
    
    /**
    * The signed IP query string argument for shared access signature.
    *
    * @const
    * @type {string}
    */
    SIGNED_IP: 'sip',
    
    /**
    * The signed protocol query string argument for shared access signature.
    *
    * @const
    * @type {string}
    */
    SIGNED_PROTOCOL: 'spr',
 
    /**
    * The signed identifier query string argument for shared access signature.
    *
    * @const
    * @type {string}
    */
    SIGNED_IDENTIFIER: 'si',
 
    /**
    * The signature query string argument for shared access signature.
    *
    * @const
    * @type {string}
    */
    SIGNATURE: 'sig',
 
    /**
    * The signed version argument for shared access signature.
    *
    * @const
    * @type {string}
    */
    SIGNED_VERSION: 'sv',
 
    /**
    * The cache control argument for shared access signature.
    *
    * @const
    * @type {string}
    */
    CACHE_CONTROL: 'rscc',
 
    /**
    * The content type argument for shared access signature.
    *
    * @const
    * @type {string}
    */
    CONTENT_TYPE: 'rsct',
 
    /**
    * The content encoding argument for shared access signature.
    *
    * @const
    * @type {string}
    */
    CONTENT_ENCODING: 'rsce',
 
    /**
    * The content language argument for shared access signature.
    *
    * @const
    * @type {string}
    */
    CONTENT_LANGUAGE: 'rscl',
 
    /**
    * The content disposition argument for shared access signature.
    *
    * @const
    * @type {string}
    */
    CONTENT_DISPOSITION: 'rscd',
 
    /**
    * The block identifier query string argument for blob service.
    *
    * @const
    * @type {string}
    */
    BLOCK_ID: 'blockid',
 
    /**
    * The block list type query string argument for blob service.
    *
    * @const
    * @type {string}
    */
    BLOCK_LIST_TYPE: 'blocklisttype',
 
    /**
    * The prefix query string argument for listing operations.
    *
    * @const
    * @type {string}
    */
    PREFIX: 'prefix',
 
    /**
    * The marker query string argument for listing operations.
    *
    * @const
    * @type {string}
    */
    MARKER: 'marker',
 
    /**
    * The maxresults query string argument for listing operations.
    *
    * @const
    * @type {string}
    */
    MAX_RESULTS: 'maxresults',
 
    /**
    * The delimiter query string argument for listing operations.
    *
    * @const
    * @type {string}
    */
    DELIMITER: 'delimiter',
 
    /**
    * The include query string argument for listing operations.
    *
    * @const
    * @type {string}
    */
    INCLUDE: 'include',
 
    /**
    * The peekonly query string argument for queue service.
    *
    * @const
    * @type {string}
    */
    PEEK_ONLY: 'peekonly',
 
    /**
    * The numofmessages query string argument for queue service.
    *
    * @const
    * @type {string}
    */
    NUM_OF_MESSAGES: 'numofmessages',
 
    /**
    * The popreceipt query string argument for queue service.
    *
    * @const
    * @type {string}
    */
    POP_RECEIPT: 'popreceipt',
 
    /**
    * The visibilitytimeout query string argument for queue service.
    *
    * @const
    * @type {string}
    */
    VISIBILITY_TIMEOUT: 'visibilitytimeout',
 
    /**
    * The messagettl query string argument for queue service.
    *
    * @const
    * @type {string}
    */
    MESSAGE_TTL: 'messagettl',
 
    /**
    * The select query string argument.
    *
    * @const
    * @type {string}
    */
    SELECT: '$select',
 
    /**
    * The filter query string argument.
    *
    * @const
    * @type {string}
    */
    FILTER: '$filter',
 
    /**
    * The top query string argument.
    *
    * @const
    * @type {string}
    */
    TOP: '$top',
 
    /**
    * The skip query string argument.
    *
    * @const
    * @type {string}
    */
    SKIP: '$skip',
 
    /**
    * The next partition key query string argument for table service.
    *
    * @const
    * @type {string}
    */
    NEXT_PARTITION_KEY: 'NextPartitionKey',
 
    /**
    * The next row key query string argument for table service.
    *
    * @const
    * @type {string}
    */
    NEXT_ROW_KEY: 'NextRowKey',
 
    /**
    * The lock identifier for service bus messages.
    *
    * @const
    * @type {string}
    */
    LOCK_ID: 'lockid',
 
    /**
    * The table name for table SAS URI's.
    *
    * @const
    * @type {string}
    */
    TABLENAME: 'tn',
 
    /**
    * The starting Partition Key for tableSAS URI's.
    *
    * @const
    * @type {string}
    */
    STARTPK: 'spk',
 
    /**
    * The starting Partition Key for tableSAS URI's.
    *
    * @const
    * @type {string}
    */
    STARTRK: 'srk',
 
    /**
    * The ending Partition Key for tableSAS URI's.
    *
    * @const
    * @type {string}
    */
    ENDPK: 'epk',
 
    /**
    * The ending Partition Key for tableSAS URI's.
    *
    * @const
    * @type {string}
    */
    ENDRK: 'erk'
  },
 
  StorageServiceClientConstants: {
    /**
    * The default protocol.
    */
    DEFAULT_PROTOCOL: 'https:',
 
    /*
    * Used environment variables.
    * @enum {string}
    */
    EnvironmentVariables: {
      AZURE_STORAGE_ACCOUNT: 'AZURE_STORAGE_ACCOUNT',
      AZURE_STORAGE_ACCESS_KEY: 'AZURE_STORAGE_ACCESS_KEY',
      AZURE_STORAGE_DNS_SUFFIX: 'AZURE_STORAGE_DNS_SUFFIX',
      AZURE_STORAGE_CONNECTION_STRING: 'AZURE_STORAGE_CONNECTION_STRING',
      HTTP_PROXY: 'HTTP_PROXY',
      HTTPS_PROXY: 'HTTPS_PROXY',
      EMULATED: 'EMULATED',
    },
 
    /**
    * Default credentials.
    */
    DEVSTORE_STORAGE_ACCOUNT: 'devstoreaccount1',
    DEVSTORE_STORAGE_ACCESS_KEY: 'Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==',
 
    /**
    * The development store URI.
    *
    * @const
    * @type {string}
    */
    DEV_STORE_URI: 'http://127.0.0.1',
 
    /**
    * Development ServiceClient URLs.
    */
    DEVSTORE_DEFAULT_PROTOCOL: 'http://',
    DEVSTORE_BLOB_HOST: '127.0.0.1:10000',
    DEVSTORE_QUEUE_HOST: '127.0.0.1:10001',
    DEVSTORE_TABLE_HOST: '127.0.0.1:10002',
 
    /**
    * Production ServiceClient URLs.
    */
    CLOUD_BLOB_HOST: 'blob.' + storageDnsSuffix,
    CLOUD_QUEUE_HOST: 'queue.' + storageDnsSuffix,
    CLOUD_TABLE_HOST: 'table.' + storageDnsSuffix,
    CLOUD_FILE_HOST: 'file.' + storageDnsSuffix
  },
 
  HttpConstants: {
    /**
    * Http Verbs
    *
    * @const
    * @enum {string}
    */
    HttpVerbs: {
      PUT: 'PUT',
      GET: 'GET',
      DELETE: 'DELETE',
      POST: 'POST',
      MERGE: 'MERGE',
      HEAD: 'HEAD'
    },
 
    /**
    * Response codes.
    *
    * @const
    * @enum {int}
    */
    HttpResponseCodes: {
      Ok: 200,
      Created: 201,
      Accepted: 202,
      NoContent: 204,
      PartialContent: 206,
      BadRequest: 400,
      Unauthorized: 401,
      Forbidden: 403,
      NotFound: 404,
      Conflict: 409,
      LengthRequired: 411,
      PreconditionFailed: 412
    }
  },
 
  CompatibleVersionConstants: {
    /**
    * Constant for the 2013-08-15 version.
    *
    * @const
    * @type {string}
    */
    AUGUST_2013: '2013-08-15',
 
    /**
    * Constant for the 2012-02-12 version.
    *
    * @const
    * @type {string}
    */
    FEBRUARY_2012: '2012-02-12'
  },
 
  BlobErrorCodeStrings: {
    INVALID_BLOCK_ID: 'InvalidBlockId',
    BLOB_NOT_FOUND: 'BlobNotFound',
    BLOB_ALREADY_EXISTS: 'BlobAlreadyExists',
    CONTAINER_ALREADY_EXISTS: 'ContainerAlreadyExists',
    CONTAINER_NOT_FOUND: 'ContainerNotFound',
    INVALID_BLOB_OR_BLOCK: 'InvalidBlobOrBlock',
    INVALID_BLOCK_LIST: 'InvalidBlockList'
  },
 
  FileErrorCodeStrings: {
    SHARE_ALREADY_EXISTS: 'ShareAlreadyExists',
    SHARE_NOT_FOUND: 'ShareNotFound',
    FILE_NOT_FOUND: 'FileNotFound'
  },
 
  QueueErrorCodeStrings: {
    QUEUE_NOT_FOUND: 'QueueNotFound',
    QUEUE_DISABLED: 'QueueDisabled',
    QUEUE_ALREADY_EXISTS: 'QueueAlreadyExists',
    QUEUE_NOT_EMPTY: 'QueueNotEmpty',
    QUEUE_BEING_DELETED: 'QueueBeingDeleted',
    POP_RECEIPT_MISMATCH: 'PopReceiptMismatch',
    INVALID_PARAMETER: 'InvalidParameter',
    MESSAGE_NOT_FOUND: 'MessageNotFound',
    MESSAGE_TOO_LARGE: 'MessageTooLarge',
    INVALID_MARKER: 'InvalidMarker'
  },
 
  /**
  * Constants for storage error strings
  *
  * More details are at: http://msdn.microsoft.com/en-us/library/azure/dd179357.aspx
  */
  StorageErrorCodeStrings: {
    // Not Modified (304): The condition specified in the conditional header(s) was not met for a read operation.
    // Precondition Failed (412): The condition specified in the conditional header(s) was not met for a write operation.
    CONDITION_NOT_MET: 'ConditionNotMet', 
    // Bad Request (400): A required HTTP header was not specified.
    MISSING_REQUIRED_HEADER: 'MissingRequiredHeader', 
    // Bad Request (400): A required XML node was not specified in the request body.
    MISSING_REQUIRED_XML_NODE: 'MissingRequiredXmlNode', 
    // Bad Request (400): One of the HTTP headers specified in the request is not supported.
    UNSUPPORTED_HEADER: 'UnsupportedHeader',
    // Bad Request (400): One of the XML nodes specified in the request body is not supported.
    UNSUPPORTED_XML_NODE: 'UnsupportedXmlNode', 
    // Bad Request (400): The value provided for one of the HTTP headers was not in the correct format.
    INVALID_HEADER_VALUE: 'InvalidHeaderValue', 
    // Bad Request (400): The value provided for one of the XML nodes in the request body was not in the correct format.
    INVALID_XML_NODE_VALUE: 'InvalidXmlNodeValue',
    // Bad Request (400): A required query parameter was not specified for this request.
    MISSING_REQUIRED_QUERY_PARAMETER: 'MissingRequiredQueryParameter',
    // Bad Request (400): One of the query parameters specified in the request URI is not supported.
    UNSUPPORTED_QUERY_PARAMETER: 'UnsupportedQueryParameter',
    // Bad Request (400): An invalid value was specified for one of the query parameters in the request URI.
    INVALID_QUERY_PARAMETER_VALUE: 'InvalidQueryParameterValue',
    // Bad Request (400): A query parameter specified in the request URI is outside the permissible range.
    OUT_OF_RANGE_QUERY_PARAMETER_VALUE: 'OutOfRangeQueryParameterValue',
    // Bad Request (400): The url in the request could not be parsed.
    REQUEST_URL_FAILED_TO_PARSE: 'RequestUrlFailedToParse',
    // Bad Request (400): The requested URI does not represent any resource on the server.
    INVALID_URI: 'InvalidUri',
    // Bad Request (400): The HTTP verb specified was not recognized by the server.
    INVALID_HTTP_VERB: 'InvalidHttpVerb',
    // Bad Request (400): The key for one of the metadata key-value pairs is empty.
    EMPTY_METADATA_KEY: 'EmptyMetadataKey',
    // Bad Request (400): The specified XML is not syntactically valid.
    INVALID_XML_DOCUMENT: 'InvalidXmlDocument',
    // Bad Request (400): The MD5 value specified in the request did not match the MD5 value calculated by the server.
    MD5_MISMATCH: 'Md5Mismatch',
    // Bad Request (400): The MD5 value specified in the request is invalid. The MD5 value must be 128 bits and Base64-encoded.
    INVALID_MD5: 'InvalidMd5',
    // Bad Request (400): One of the request inputs is out of range.
    OUT_OF_RANGE_INPUT: 'OutOfRangeInput',
    // Bad Request (400): The authentication information was not provided in the correct format. Verify the value of Authorization header.
    INVALID_AUTHENTICATION_INFO: 'InvalidAuthenticationInfo',
    // Bad Request (400): One of the request inputs is not valid.
    INVALID_INPUT: 'InvalidInput',
    // Bad Request (400): The specified metadata is invalid. It includes characters that are not permitted.
    INVALID_METADATA: 'InvalidMetadata',
    // Bad Request (400): The specifed resource name contains invalid characters.
    INVALID_RESOURCE_NAME: 'InvalidResourceName',
    // Bad Request (400): The size of the specified metadata exceeds the maximum size permitted.
    METADATA_TOO_LARGE: 'MetadataTooLarge',
    // Bad Request (400): Condition headers are not supported.
    CONDITION_HEADER_NOT_SUPPORTED: 'ConditionHeadersNotSupported',
    // Bad Request (400): Multiple condition headers are not supported.
    MULTIPLE_CONDITION_HEADER_NOT_SUPPORTED: 'MultipleConditionHeadersNotSupported',
    // Forbidden (403): Server failed to authenticate the request. Make sure the value of the Authorization header is formed correctly including the signature.
    AUTHENTICATION_FAILED: 'AuthenticationFailed',
    // Forbidden (403): Read-access geo-redundant replication is not enabled for the account.
    // Forbidden (403): Write operations to the secondary location are not allowed.
    // Forbidden (403): The account being accessed does not have sufficient permissions to execute this operation.
    INSUFFICIENT_ACCOUNT_PERMISSIONS: 'InsufficientAccountPermissions',
    // Not Found (404): The specified resource does not exist.
    RESOURCE_NOT_FOUND: 'ResourceNotFound',
    // Forbidden (403): The specified account is disabled.
    ACCOUNT_IS_DISABLED: 'AccountIsDisabled',
    // Method Not Allowed (405): The resource doesn't support the specified HTTP verb.
    UNSUPPORTED_HTTP_VERB: 'UnsupportedHttpVerb',
    // Conflict (409): The specified account already exists. 
    ACCOUNT_ALREADY_EXISTS: 'AccountAlreadyExists',
    // Conflict (409): The specified account is in the process of being created.
    ACCOUNT_BEING_CREATED: 'AccountBeingCreated',
    // Conflict (409): The specified resource already exists.
    RESOURCE_ALREADY_EXISTS: 'ResourceAlreadyExists',
    // Conflict (409): The specified resource type does not match the type of the existing resource.
    RESOURCE_TYPE_MISMATCH: 'ResourceTypeMismatch',
    // Length Required (411): The Content-Length header was not specified.
    MISSING_CONTENT_LENGTH_HEADER: 'MissingContentLengthHeader',
    // Request Entity Too Large (413): The size of the request body exceeds the maximum size permitted.
    REQUEST_BODY_TOO_LARGE: 'RequestBodyTooLarge',
    // Requested Range Not Satisfiable (416): The range specified is invalid for the current size of the resource.
    INVALID_RANGE: 'InvalidRange',
    // Internal Server Error (500): The server encountered an internal error. Please retry the request.
    INTERNAL_ERROR: 'InternalError',
    // Internal Server Error (500): The operation could not be completed within the permitted time.
    OPERATION_TIMED_OUT: 'OperationTimedOut',
    // Service Unavailable (503): The server is currently unable to receive requests. Please retry your request. 
    SERVER_BUSY: 'ServerBusy',
 
    // Legacy error code strings
    UPDATE_CONDITION_NOT_SATISFIED: 'UpdateConditionNotSatisfied',
    CONTAINER_NOT_FOUND: 'ContainerNotFound',
    CONTAINER_ALREADY_EXISTS: 'ContainerAlreadyExists',
    CONTAINER_DISABLED: 'ContainerDisabled',
    CONTAINER_BEING_DELETED: 'ContainerBeingDeleted',
  },
 
  TableErrorCodeStrings: {
    XMETHOD_NOT_USING_POST: 'XMethodNotUsingPost',
    XMETHOD_INCORRECT_VALUE: 'XMethodIncorrectValue',
    XMETHOD_INCORRECT_COUNT: 'XMethodIncorrectCount',
    TABLE_HAS_NO_PROPERTIES: 'TableHasNoProperties',
    DUPLICATE_PROPERTIES_SPECIFIED: 'DuplicatePropertiesSpecified',
    TABLE_HAS_NO_SUCH_PROPERTY: 'TableHasNoSuchProperty',
    DUPLICATE_KEY_PROPERTY_SPECIFIED: 'DuplicateKeyPropertySpecified',
    TABLE_ALREADY_EXISTS: 'TableAlreadyExists',
    TABLE_NOT_FOUND: 'TableNotFound',
    ENTITY_NOT_FOUND: 'EntityNotFound',
    ENTITY_ALREADY_EXISTS: 'EntityAlreadyExists',
    PARTITION_KEY_NOT_SPECIFIED: 'PartitionKeyNotSpecified',
    OPERATOR_INVALID: 'OperatorInvalid',
    UPDATE_CONDITION_NOT_SATISFIED: 'UpdateConditionNotSatisfied',
    PROPERTIES_NEED_VALUE: 'PropertiesNeedValue',
    PARTITION_KEY_PROPERTY_CANNOT_BE_UPDATED: 'PartitionKeyPropertyCannotBeUpdated',
    TOO_MANY_PROPERTIES: 'TooManyProperties',
    ENTITY_TOO_LARGE: 'EntityTooLarge',
    PROPERTY_VALUE_TOO_LARGE: 'PropertyValueTooLarge',
    INVALID_VALUE_TYPE: 'InvalidValueType',
    TABLE_BEING_DELETED: 'TableBeingDeleted',
    TABLE_SERVER_OUT_OF_MEMORY: 'TableServerOutOfMemory',
    PRIMARY_KEY_PROPERTY_IS_INVALID_TYPE: 'PrimaryKeyPropertyIsInvalidType',
    PROPERTY_NAME_TOO_LONG: 'PropertyNameTooLong',
    PROPERTY_NAME_INVALID: 'PropertyNameInvalid',
    BATCH_OPERATION_NOT_SUPPORTED: 'BatchOperationNotSupported',
    JSON_FORMAT_NOT_SUPPORTED: 'JsonFormatNotSupported',
    METHOD_NOT_ALLOWED: 'MethodNotAllowed',
    NOT_IMPLEMENTED: 'NotImplemented'
  },
 
  ConnectionStringKeys: {
    USE_DEVELOPMENT_STORAGE_NAME: 'UseDevelopmentStorage',
    DEVELOPMENT_STORAGE_PROXY_URI_NAME: 'DevelopmentStorageProxyUri',
    DEFAULT_ENDPOINTS_PROTOCOL_NAME: 'DefaultEndpointsProtocol',
    ACCOUNT_NAME_NAME: 'AccountName',
    ACCOUNT_KEY_NAME: 'AccountKey',
    BLOB_ENDPOINT_NAME: 'BlobEndpoint',
    FILE_ENDPOINT_NAME: 'FileEndpoint',
    QUEUE_ENDPOINT_NAME: 'QueueEndpoint',
    TABLE_ENDPOINT_NAME: 'TableEndpoint',
    SHARED_ACCESS_SIGNATURE_NAME: 'SharedAccessSignature',
    ENDPOINT_SUFFIX_NAME: 'EndpointSuffix',
    BLOB_BASE_DNS_NAME: 'blob.core.windows.net',
    FILE_BASE_DNS_NAME: 'file.core.windows.net',
    QUEUE_BASE_DNS_NAME: 'queue.core.windows.net',
    TABLE_BASE_DNS_NAME: 'table.core.windows.net'
  }
};
 
module.exports = Constants;
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/util/date.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/util/date.js

Statements: 25% (4 / 16)      Branches: 100% (0 / 0)      Functions: 0% (0 / 4)      Lines: 25% (4 / 16)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70                                                        1                       1                       1                       1          
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
/**
* Date/time related helper functions
* @module date
* 
*/
 
/**
* Generates a Date object which is in the given days from now.
* 
* @param {int} days The days timespan.
* @return {Date}
*/
exports.daysFromNow = function (days) {
  var date = new Date();
  date.setDate(date.getDate() + days);
  return date;
};
 
/**
* Generates a Date object which is in the given hours from now.
*
* @param {int} hours The hours timespan.
* @return {Date}
*/
exports.hoursFromNow = function (hours) {
  var date = new Date();
  date.setHours(date.getHours() + hours);
  return date;
};
 
/**
* Generates a Date object which is in the given minutes from now.
*
* @param {int} minutes The minutes timespan.
* @return {Date}
*/
exports.minutesFromNow = function (minutes) {
  var date = new Date();
  date.setMinutes(date.getMinutes() + minutes);
  return date;
};
 
/**
* Generates a Date object which is in the given seconds from now.
*
* @param {int} seconds The seconds timespan.
* @return {Date}
*/
exports.secondsFromNow = function (seconds) {
  var date = new Date();
  date.setSeconds(date.getSeconds() + seconds);
  return date;
};
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/util/iso8061date.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/util/iso8061date.js

Statements: 16.67% (3 / 18)      Branches: 0% (0 / 2)      Functions: 0% (0 / 3)      Lines: 16.67% (3 / 18)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67                                1                                 1                     1                                            
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var rightPad = function (n, number) {
  var currentN = '' + n;
  while (currentN.length < number) {
    currentN = currentN + '0';
  }
 
  return currentN;
};
 
/**
* Formats a date into an iso 8061 string.
*
* @param {date}    date The date to format.
* @param {bool}    skipMilliseconds Boolean value indicating if the miliseconds part of the date should not be included.
* @param {integer} millisecondsPading Number of digits to left pad the miliseconds.
* @return {string} The date formated in the ISO 8061 date format.
*/
exports.format = function (date) {
  var dateString = date.toISOString();
  return dateString.substring(0, dateString.length - 1) + '0000Z';
};
 
/**
* Parses an ISO 8061 date string into a date object.
*
* @param {string} stringDateTime The string with the date to parse in the ISO 8061 format.
* @return {date} The parsed date.
*/
exports.parse = function (stringDateTime) {
  var parts = stringDateTime.split('T');
  var ymd = parts[0].split('-');
  var time = parts[1].split('.');
  var hms = time[0].split(':');
  var ms = 0;
  if (time[1]) {
    ms = time[1].split('Z');
  }
 
  var date = new Date(Date.UTC(
    parseInt(ymd[0], 10),
    parseInt(ymd[1], 10) - 1,
    parseInt(ymd[2], 10),
    parseInt(hms[0], 10),
    parseInt(hms[1], 10),
    parseInt(hms[2], 10),
    Math.round(parseInt(rightPad(ms[0], 7), 10) / 10000)
  ));
 
  return date;
};
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/util/patch-xmlbuilder.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/util/patch-xmlbuilder.js

Statements: 28.57% (2 / 7)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 28.57% (2 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32                                    1         1                
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
'use strict';
 
var XMLBuilder = require('xmlbuilder/lib/XMLBuilder');
 
// Patch xmlbuilder to allow Unicode surrogate pair code
// points in XML bodies
 
XMLBuilder.prototype.assertLegalChar = function(str) {
  var chars, chr;
  chars = /[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uFFFE-\uFFFF]/;
  chr = str.match(chars);
  if (chr) {
    throw new Error('Invalid character (' + chr + ') in string: ' + str);
  }
};
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/util/sr.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/util/sr.js

Statements: 100% (3 / 3)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (3 / 3)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77                                1   1                                                                                                                 1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
exports = module.exports;
 
var SR = {
  ANONYMOUS_ACCESS_BLOBSERVICE_ONLY: 'Anonymous access is only valid for the BlobService.',
  ARGUMENT_NULL_OR_EMPTY: 'The argument must not be null or an empty string. Argument name: %s.',
  ARGUMENT_NULL_OR_UNDEFINED: 'The argument must not be null or undefined. Argument name: %s.',
  ARGUMENT_OUT_OF_RANGE_ERROR: 'The argument is out of range. Argument name: %s, Value passed: %s.',
  BATCH_ONE_PARTITION_KEY: 'All entities in the batch must have the same PartitionKey value.',
  BATCH_ONE_RETRIEVE: 'If a retrieve operation is part of a batch, it must be the only operation in the batch.',
  BATCH_TOO_LARGE: 'Batches must not contain more than 100 operations.',
  BLOB_INVALID_SEQUENCE_NUMBER: 'The sequence number may not be specified for an increment operation.',
  BLOB_TYPE_MISMATCH: 'Blob type of the blob reference doesn\'t match blob type of the blob.',
  CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY: 'Cannot create Shared Access Signature unless the Account Name and Key are used to create the ServiceClient.',
  CONTENT_LENGTH_MISMATCH: 'An incorrect number of bytes was read from the connection. The connection may have been closed.',
  CONTENT_TYPE_MISSING: 'Content-Type response header is missing or invalid.',
  EMPTY_BATCH: 'Batch must not be empty.',
  EXCEEDED_SIZE_LIMITATION: 'Upload exceeds the size limitation. Max size is %s but the current size is %s',
  HASH_MISMATCH: 'Hash mismatch (integrity check failed), Expected value is %s, retrieved %s.',
  INCORRECT_ENTITY_KEYS: 'PartitionKey and RowKey must be specified as strings in the entity object.',
  INVALID_BLOB_LENGTH: 'createBlockBlobFromText requires the size of text to be less than 64MB. Please use createBlockBlobFromLocalFile or createBlockBlobFromStream to upload large blobs.',
  INVALID_CONNECTION_STRING: 'Connection strings must be of the form "key1=value1;key2=value2".',
  INVALID_CONNECTION_STRING_BAD_KEY: 'Connection string contains unrecognized key: "%s"',
  INVALID_CONNECTION_STRING_DUPLICATE_KEY: 'Connection string contains duplicate key: "%s"',
  INVALID_CONNECTION_STRING_EMPTY_KEY: 'Connection strings must not contain empty keys.',
  INVALID_DELETE_SNAPSHOT_OPTION: 'The deleteSnapshots option cannot be included when deleting a specific snapshot using the snapshotId option.',
  INVALID_EDM_TYPE: 'The value \'%s\' does not match the type \'%s\'.',
  INVALID_FILE_LENGTH: 'createFileFromText requires the size of text to be less than 4MB. Please use createFileFromLocalFile or createFileFromStream to upload large files.',
  INVALID_FILE_RANGE_FOR_UPDATE: 'Range size should be less than 4MB for a file range update operation.',
  INVALID_HEADERS: 'Headers are not supported in the 2012-02-12 version.',
  INVALID_MESSAGE_ID: 'Message ID cannot be null or undefined for deleteMessage and updateMessage operations.',
  INVALID_PAGE_BLOB_LENGTH: 'Page blob length must be multiple of 512.',
  INVALID_PAGE_END_OFFSET: 'Page end offset must be multiple of 512.',
  INVALID_PAGE_RANGE_FOR_UPDATE: 'Page range size should be less than 4MB for a page update operation.',
  INVALID_PAGE_START_OFFSET: 'Page start offset must be multiple of 512.',
  INVALID_POP_RECEIPT: 'Pop Receipt cannot be null or undefined for deleteMessage and updateMessage operations.',
  INVALID_PROPERTY_RESOLVER: 'The specified property resolver returned an invalid type. %s:{_:%s,$:%s }',
  INVALID_RANGE_FOR_MD5: 'The requested range should be less than 4MB when contentMD5 is expected from the server',
  INVALID_SAS_VERSION: 'SAS Version ? is invalid. Valid versions include: ?.',
  INVALID_SAS_TOKEN: 'The SAS token should not contain api-version.',
  INVALID_SIGNED_IDENTIFIERS: 'Signed identifiers need to be a hash object with key as the id and the value as the access policy.',
  INVALID_STREAM_LENGTH: 'The length of the provided stream is invalid.',
  INVALID_STRING_ERROR: 'Invalid string error.',
  INVALID_TABLE_OPERATION: 'Operation not found: %s',
  INVALID_TEXT_LENGTH: 'The length of the provided text is invalid.',
  MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION: 'The client could not finish the operation within specified maximum execution timeout.',
  MD5_NOT_POSSIBLE: 'MD5 cannot be calculated for an existing blob because it would require reading the existing data. Please disable storeBlobContentMD5.',
  MD5_NOT_PRESENT_ERROR: 'MD5 does not exist. If you do not want to force validation, please disable useTransactionalMD5.',
  METADATA_KEY_INVALID: 'The key for one of the metadata key-value pairs is null, empty, or whitespace.',
  METADATA_VALUE_INVALID: 'The value for one of the metadata key-value pairs is null, empty, or whitespace.',
  NO_CREDENTIALS_PROVIDED: 'Credentials must be provided when creating a service client.',
  PRIMARY_ONLY_COMMAND: 'This operation can only be executed against the primary storage location.',
  QUERY_OPERATOR_REQUIRES_WHERE: '%s operator needs to be used after where.',
  SECONDARY_ONLY_COMMAND: 'This operation can only be executed against the secondary storage location.',
  STORAGE_HOST_LOCATION_REQUIRED: 'The host for the storage service must be specified.',
  STORAGE_HOST_MISSING_LOCATION: 'The host for the target storage location is not specified. Please consider changing the request\'s location mode.',
  TYPE_NOT_SUPPORTED: 'Type not supported when sending data to the service: ',
  MAX_BLOB_SIZE_CONDITION_NOT_MEET: 'Append block data should not exceed the maximum blob size condition value.',
};
 
module.exports = SR;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/util/storageutilities.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/util/storageutilities.js

Statements: 100% (2 / 2)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (2 / 2)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43                                            1                                     1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Expose 'StorageUtilities'.
 
/**
* Defines constants, enums, and utility functions for use with storage.
* @namespace
*/
var StorageUtilities = {
	/**
  * Specifies the location mode used to decide which location the request should be sent to.
  *
  * @const
  * @enum {number}
  */
  LocationMode: {
    /** The primary location only */
    PRIMARY_ONLY: 0,
    /** The primary location first, then the secondary */
    PRIMARY_THEN_SECONDARY: 1,
    /** The secondary location only */
    SECONDARY_ONLY: 2,
    /** The secondary location first, then the primary */
    SECONDARY_THEN_PRIMARY: 3
  }
};
 
module.exports = StorageUtilities;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/util/util.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/util/util.js

Statements: 23.18% (51 / 220)      Branches: 0.77% (1 / 130)      Functions: 2.38% (1 / 42)      Lines: 23.39% (51 / 218)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620                                1 1 1 1 1 1 1 1 1 1               1                           1                             1                         1                   1                   1                   1                   1                   1                 1               1                             1                   1                                     1                                 1                             1                           1                           1                             1                                 1                                             1                                                     1                                               1         1                     1 2 2             1                                                         1                                                                   1                       1 1                                                                     1             1                           1                               1             1         1                       1                                                     1                                               1                                      
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var fs = require('fs');
var path = require('path');
var _ = require('underscore');
var util = require('util');
var url = require('url');
var stream = require('stream');
var Constants = require('./constants');
var Md5Wrapper = require('../md5-wrapper');
var StorageUtilities = require('./storageutilities');
var SR = require('./sr');
 
/**
* Trim the default port in the url.
*
* @param {string} uri The URI to be encoded.
* @return {string} The URI without defualt port.
*/
exports.trimPortFromUri = function (uri) {
  var uri = url.parse(uri);
  if ((uri.protocol === Constants.HTTPS && uri.port == Constants.DEFAULT_HTTPS_PORT) || (uri.protocol === Constants.HTTP && uri.port == Constants.DEFAULT_HTTP_PORT)) {
    uri.host = uri.hostname;
  }
  return url.format(uri);
};
 
/**
* Encodes an URI.
*
* @param {string} uri The URI to be encoded.
* @return {string} The encoded URI.
*/
exports.encodeUri = function (uri) {
  return encodeURIComponent(uri)
    .replace(/!/g, '%21')
    .replace(/'/g, '%27')
    .replace(/\(/g, '%28')
    .replace(/\)/g, '%29')
    .replace(/\*/g, '%2A');
};
 
/**
* Returns the number of keys (properties) in an object.
*
* @param {object} value The object which keys are to be counted.
* @return {number} The number of keys in the object.
*/
exports.objectKeysLength = function (value) {
  if (!value) {
    return 0;
  }
 
  return _.keys(value).length;
};
 
/**
* Checks if in a browser environment.
*
* @return {bool} True if in a browser environment, false otherwise.
*/
exports.isBrowser = function () {
  return typeof window !== 'undefined';
};
 
/**
* Checks if a value is null or undefined.
*
* @param {object} value The value to check for null or undefined.
* @return {bool} True if the value is null or undefined, false otherwise.
*/
exports.objectIsNull = function (value) {
  return _.isNull(value) || _.isUndefined(value);
};
 
/**
* Checks if an object is empty.
*
* @param {object} object The object to check if it is null.
* @return {bool} True if the object is empty, false otherwise.
*/
exports.objectIsEmpty = function (object) {
  return _.isEmpty(object);
};
 
/**
* Determines if an object contains an integer number.
*
* @param {object}  value  The object to assert.
* @return {bool} True if the object contains an integer number; false otherwise.
*/
exports.objectIsInt = function (value) {
  return typeof value === 'number' && parseFloat(value) == parseInt(value, 10) && !isNaN(value);
};
 
/**
* Determines if an object is a NaN.
*
* @param {object}  value  The object to assert.
* @return {bool} True if the object is a NaN; false otherwise.
*/
exports.objectIsNaN = function (value) {
  return typeof(value) === 'number' && isNaN(value);
};
 
/**
* Checks if an object is a string.
*
* @param {object} object The object to check if it is a string.
* @return {bool} True if the object is a string, false otherwise.
*/
exports.objectIsString = function (object) {
  return _.isString(object);
};
 
/**
* Check if an object is a function
* @param {object} object The object to check whether it is function
* @return {bool} True if the specified object is function, otherwise false
*/
exports.objectIsFunction = function (object) {
  return _.isFunction(object);
};
 
 
/**
* Front zero padding of string to sepcified length
*/
exports.zeroPaddingString = function(str, len) {
  var paddingStr = '0000000000' + str;
  if(paddingStr.length < len) {
    return exports.zeroPaddingString(paddingStr, len);
  } else {
    return paddingStr.substr(-1 * len);
  }
};
 
/**
* Checks if a value is an empty string, null or undefined.
*
* @param {object} value The value to check for an empty string, null or undefined.
* @return {bool} True if the value is an empty string, null or undefined, false otherwise.
*/
exports.stringIsEmpty = function (value) {
  return _.isNull(value) || _.isUndefined(value) || value === '';
};
 
/**
* Checks if a value is null, empty, undefined or consists only of white-space characters.
*
* @param {object} value The value to check for null, empty, undefined and white-space only characters.
* @return {bool} True if the value is an empty string, null, undefined, or consists only of white-space characters, false otherwise.
*/
exports.IsNullOrEmptyOrUndefinedOrWhiteSpace = function (value) {
  if(_.isNull(value) || _.isUndefined(value) || value === '') {
    return true;
  }
 
  if(_.isString(value) && value.trim().length === 0) {
    return true;
  }
 
  return false;
};
 
/**
* Formats a text replacing '?' by the arguments.
*
* @param {string}       text      The string where the ? should be replaced.
* @param {array}        arguments Value(s) to insert in question mark (?) parameters.
* @return {string}
*/
exports.stringFormat = function (text) {
  if (arguments.length > 1) {
    for (var i = 1; text.indexOf('?') !== -1; i++) {
      text = text.replace('?', arguments[i]);
    }
  }
 
  return text;
};
 
/**
* Determines if a string starts with another.
*
* @param {string}       text      The string to assert.
* @param {string}       prefix    The string prefix.
* @return {Bool} True if the string starts with the prefix; false otherwise.
*/
exports.stringStartsWith = function (text, prefix) {
  if (_.isNull(prefix)) {
    return true;
  }
 
  return text.substr(0, prefix.length) === prefix;
};
 
/**
* Determines if a string ends with another.
*
* @param {string}       text      The string to assert.
* @param {string}       suffix    The string suffix.
* @return {Bool} True if the string ends with the suffix; false otherwise.
*/
exports.stringEndsWith = function (text, suffix) {
  if (_.isNull(suffix)) {
    return true;
  }
 
  return text.substr(text.length - suffix.length) === suffix;
};
 
/**
* Removes the BOM from a string.
*
* @param {string} str The string from where the BOM is to be removed
* @return {string} The string without the BOM.
*/
exports.removeBOM = function (str) {
  if (str.charCodeAt(0) === 0xfeff || str.charCodeAt(0) === 0xffef) {
    str = str.substring(1);
  }
 
  return str;
};
 
/**
* Merges multiple objects.
*
* @param {object} object The objects to be merged
* @return {object} The merged object.
*/
exports.merge = function () {
  return _.extend.apply(this, arguments);
};
 
/**
* Checks if a value exists in an array. The comparison is done in a case
* insensitive manner.
*
* @param {string} needle     The searched value.
* @param {array}  haystack   The array.
*
* @static
*
* @return {boolean}
*/
exports.inArrayInsensitive = function (needle, haystack) {
  return _.contains(_.map(haystack, function (h) { return h.toLowerCase(); }), needle.toLowerCase());
};
 
/**
* Returns the specified value of the key passed from object and in case that
* this key doesn't exist, the default value is returned. The key matching is
* done in a case insensitive manner.
*
* @param {string} key      The array key.
* @param {object} haystack The object to be used.
* @param {mix}    default  The value to return if $key is not found in $array.
*
* @static
*
* @return mix
*/
exports.tryGetValueInsensitive = function (key, haystack, defaultValue) {
  if (haystack) {
    for (var i in haystack) {
      if (haystack.hasOwnProperty(i) && i.toString().toLowerCase() === key.toString().toLowerCase()) {
        return haystack[i];
      }
    }
  }
 
  return defaultValue;
};
 
/**
* Returns the value in a chained object.
*
* @param {object} object   The object with the values.
* @param {array}  keys     The keys.
* @param {mix}    default  The value to return if $key is not found in $array.
*
* @static
*
* @return mix
*/
exports.tryGetValueChain = function (object, keys, defaultValue) {
  if (keys.length === 0) {
    return object;
  }
 
  var currentKey = keys.shift();
  if (object && object[currentKey] !== undefined) {
    return exports.tryGetValueChain(object[currentKey], keys, defaultValue);
  }
 
  return defaultValue;
};
 
/**
* Set the value of an inner property of an object.
*
* @param {object} object   The target object.
* @param {array}  keys     The property chain keys.
* @param {mix}    object   The value to be set.
*
* @static
 
* @example
* // Set targetObject.propA.propB to 'testValue'
* var targetObject = {};
* util.setObjectInnerPropertyValue(targetObject, ['propA', 'propB'], 'testValue');
*/
exports.setObjectInnerPropertyValue = function(object, propertyChainKeys, value){
  if(!object || propertyChainKeys.length < 1) {
    return;
  }
 
  var currentKey = propertyChainKeys.shift();
  if(propertyChainKeys.length === 0) {
    object[currentKey] = value;
    return;
  }
  
  if (!object[currentKey]) {
    object[currentKey] = {};
  }
  
  exports.setObjectInnerPropertyValue(object[currentKey], propertyChainKeys, value);
};
 
/**
* Rounds a date off to seconds.
*
* @param {Date} a date
* @return {string} the date in ISO8061 format, with no milliseconds component
*/
exports.truncatedISO8061Date = function (date) {
  var dateString = date.toISOString();
  return dateString.substring(0, dateString.length - 5) + 'Z';
};
 
exports.normalizeArgs = function (optionsOrCallback, callback, result) {
  var options = {};
  if(_.isFunction(optionsOrCallback) && !callback) {
    callback = optionsOrCallback;
  } else if (optionsOrCallback) {
    options = optionsOrCallback;
  }
 
  result(options, callback);
};
 
exports.getNodeVersion = function () {
  var parsedVersion = process.version.split('.');
  return {
    major: parseInt(parsedVersion[0].substr(1), 10),
    minor: parseInt(parsedVersion[1], 10),
    patch: parseInt(parsedVersion[2], 10)
  };
};
 
exports.analyzeStream = function (stream, calculateMD5, callback) {
  var digest = null;
  var length = 0;
  if (calculateMD5) {
    digest = new Md5Wrapper().createMd5Hash();
  }
 
  stream.on('data', function (chunk) {
    if (calculateMD5) {
      digest.update(chunk);
    }
 
    length += chunk.length;
  });
 
  stream.on('end', function () {
    var md5 = null;
    if (calculateMD5) {
      md5 = digest.digest('base64');
    }
 
    callback(length, md5);
  });
};
 
/**
* Calculate md5sum for the stream
* @ignore
*/
exports.calculateMD5 = function(readStream, bufferLength, options, callback) {
  var internalBuff = new Buffer(bufferLength);
  var index = 0;
  var internalHash = new Md5Wrapper().createMd5Hash();
  readStream.on('data', function(data) {
    if (index + data.length > bufferLength) {
      var copyLength = bufferLength - index;
      if (copyLength > 0) {
        data = data.slice(0, copyLength);
        data.copy(internalBuff, index);
        internalHash.update(data);
        index += copyLength;
      }
      readStream.emit('end');
    } else {
      data.copy(internalBuff, index);
      internalHash.update(data);
      index += data.length;
    }
  }).on('end', function() {
    if (!readStream.endEmitted) {
      internalBuff = internalBuff.slice(0, index);
      var contentMD5 = internalHash.digest('base64');
      // Set the flag to be compatible with Nodejs 0.10 which will keep emitting data from 
      // the file stream when the read stream has emitted the end event from its listner. 
      readStream.endEmitted = true;
      callback(internalBuff, contentMD5);
    }
  });
};
 
/**
* Whether the content of buffer is all zero
*/
exports.isBufferAllZero = function (buffer) {
  for(var i = 0, len = buffer.length; i < len; i++) {
    if (buffer[i] !== 0) {
      return false;
    }
  }
  return true;
};
 
/**
* Write zero to stream
*/
var zeroBuffer = null;
exports.writeZerosToStream = function (stream, length, md5Hash, progressCallback, callback) {
  var defaultBufferSize = Constants.BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES;
  var bufferSize = Math.min(defaultBufferSize, length);
  var remaining = length - bufferSize;
  var buffer = null;
  if (bufferSize == defaultBufferSize) {
    if (!zeroBuffer) {
      zeroBuffer = new Buffer(defaultBufferSize);
      zeroBuffer.fill(0);
    }
    buffer = zeroBuffer;
  } else {
    buffer = new Buffer(bufferSize);
    buffer.fill(0);
  }
  if (md5Hash) {
    md5Hash.update(buffer);
  }
  //We can only write the entire buffer to stream instead of part of buffer.
  return stream.write(buffer, function () {
    if (exports.objectIsFunction(progressCallback)) {
      progressCallback(null, buffer.length);
    }
    buffer = null;
    if (remaining > 0) {
      exports.writeZerosToStream(stream, remaining, md5Hash, progressCallback, callback);
    } else if (exports.objectIsFunction(callback)) {
      callback(null, null);
    }
  });
};
 
/**
* Calculate md5sum for the content
*/
exports.getContentMd5 = function (content, encoding) {
  if (!encoding) encoding = 'base64';
  var internalHash = new Md5Wrapper().createMd5Hash();
  internalHash.update(content, 'utf8');
  return internalHash.digest(encoding);
};
 
exports.getNextLocation = function(lastLocation, locationMode) {
  switch(locationMode) {
  case StorageUtilities.LocationMode.PRIMARY_ONLY:
    return Constants.StorageLocation.PRIMARY;
  case StorageUtilities.LocationMode.SECONDARY_ONLY:
    return Constants.StorageLocation.SECONDARY;
  case StorageUtilities.LocationMode.PRIMARY_THEN_SECONDARY:
  case StorageUtilities.LocationMode.SECONDARY_THEN_PRIMARY:
    return (lastLocation === Constants.StorageLocation.PRIMARY) ? Constants.StorageLocation.SECONDARY : Constants.StorageLocation.PRIMARY;
  default:
    throw new RangeError(util.format(SR.ARGUMENT_OUT_OF_RANGE_ERROR, 'locationMode', locationMode));
  }
};
 
exports.getNextListingLocationMode = function (token) {
  if(_.isNull(token) || _.isUndefined(token)) {
    return Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
  }
  else {
    switch (token.targetLocation) {
    case Constants.StorageLocation.PRIMARY:
      return Constants.RequestLocationMode.PRIMARY_ONLY;
    case Constants.StorageLocation.SECONDARY:
      return Constants.RequestLocationMode.SECONDARY_ONLY;
    default:
      throw new RangeError(util.format(SR.ARGUMENT_OUT_OF_RANGE_ERROR, 'targetLocation', token.targetLocation));
    }
  }
};
 
exports.isStreamPaused = function (object) {
  if (object instanceof stream) {
    return object._paused === true || (object._readableState && object._readableState.flowing === false);
  }
  return false;
};
 
exports.pathExistsSync = fs.existsSync ? fs.existsSync : path.existsSync;
 
/**
* Parse copy progress string in the format of bytesCopied/totalBytes
*/
exports.parseCopyProgress = function (progress) {
  if (typeof progress != 'string' || progress.indexOf('/') === -1) {
    return {};
  }
  
  var progressInfo = progress.split('/');
  return { bytesCopied: progressInfo[0], totalBytes: progressInfo[1] };
};
 
/**
* The list of the properties should be normalized with explicit mapping
*/
var normalizePropertyNameExceptionList = {
  'x-ms-blob-sequence-number': 'sequenceNumber',
  'content-Type': 'contentSettings.contentType',
  'content-Encoding': 'contentSettings.contentEncoding',
  'content-Language': 'contentSettings.contentLanguage',
  'cache-Control': 'contentSettings.cacheControl',
  'content-Disposition': 'contentSettings.contentDisposition',
  'content-MD5': 'contentSettings.contentMD5',
  'leaseId': 'lease.id',
  'leaseStatus': 'lease.status',
  'leaseDuration': 'lease.duration',
  'leaseState': 'lease.state',
  'copyId': 'copy.id',
  'copyStatus': 'copy.status',
  'copySource': 'copy.source',
  'copyProgress': 'copy.progress',
  'copyCompletionTime': 'copy.completionTime',
  'copyStatusDescription': 'copy.statusDescription',
  'copyDestinationSnapshot': 'copy.destinationSnapshot',
  'publicAccess': 'publicAccessLevel',
  'incrementalCopy': 'isIncrementalCopy'
};
 
/**
* Normalize the property name from XML to keep consistent with 
* the name defined in the property headers
*/
exports.normalizePropertyNameFromXML = function (propertyName) {
  if (this.IsNullOrEmptyOrUndefinedOrWhiteSpace(propertyName)) {
    return '';
  }
  
  propertyName = propertyName.trim();
  propertyName = propertyName[0].toLowerCase() + propertyName.substring(1);
  // So far the cases are:
  //   for the 'last-modified' property in listing resources
  //   for the 'content-*' properties in listing resources
  //   for the 'cache-control' property in listing blobs
  //   for the 'x-ms-blob-sequence-number' in listing blobs
  if (propertyName in normalizePropertyNameExceptionList) {
    return normalizePropertyNameExceptionList[propertyName];
  } else if (propertyName.toLowerCase().indexOf('-') != -1) {
    return propertyName.replace('-', '');
  } else {
    return propertyName;
  }
};
 
/**
* Set the property value from XML
*/
exports.setPropertyValueFromXML = function (result, xmlNode, toNormalize) {
  for (var subPropertyName in xmlNode) {
    if (xmlNode.hasOwnProperty(subPropertyName)) {
      if (toNormalize) {
        var propertyChain = this.normalizePropertyNameFromXML(subPropertyName).split('.');
        exports.setObjectInnerPropertyValue(result, propertyChain, xmlNode[subPropertyName]);
      } else {
        result[subPropertyName.toLowerCase()] = xmlNode[subPropertyName];
      }
      
      if (subPropertyName.toLowerCase() === 'copyprogress') {
        var info = this.parseCopyProgress(xmlNode[subPropertyName]);
        exports.setObjectInnerPropertyValue(result, ['copy', 'bytesCopied'], parseInt(info.bytesCopied));
        exports.setObjectInnerPropertyValue(result, ['copy', 'totalBytes'], parseInt(info.totalBytes));
      }
    }
  }
};
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/util/validate.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/common/util/validate.js

Statements: 16.91% (35 / 207)      Branches: 0% (0 / 103)      Functions: 0% (0 / 44)      Lines: 16.91% (35 / 207)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500                                1 1   1 1 1 1 1 1 1 1 1   1   1                                               1                                               1                         1                                                         1                                               1                               1                   1                                               1                                             1                                                 1                                           1                                             1                                                                       1                                                                 1                                     1                                         1                                   1       1       1                                                                                                                                         1         1 1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var _ = require('underscore');
var util = require('util');
 
var constants = require('./../util/constants');
var blobConstants = constants.BlobConstants;
var FileUtilities = require('./../../services/file/fileutilities');
var azureutil = require('./util');
var SR = require('./sr');
var check = require('validator');
var errors = require('../errors/errors');
var ArgumentError = errors.ArgumentError;
var ArgumentNullError = errors.ArgumentNullError;
 
exports = module.exports;
 
function initCallback(callbackParam, resultsCb) {
  var fail;
  if (callbackParam) {
    fail = function (err) {
      callbackParam(err);
      return false;
    };
  } else {
    fail = function (err) {
      throw err;
    };
    callbackParam = function () {};
  }
 
  resultsCb(fail, callbackParam);
}
 
/**
* Checks if the given value is a valid enumeration or not.
*
* @param {object} value     The value to validate.
* @param {object} list      The enumeration values.
* @return {boolean}
*/
exports.isValidEnumValue = function (value, list, callback) {
  var fail;
  
  initCallback(callback, function (f, cb) {
    fail = f;
    callback = cb;
  });
 
  if (!list.some(function (current) {
    return current.toLowerCase() === value.toLowerCase();
  })) {
    return fail(new RangeError(util.format('Invalid value: %s. Options are: %s.', value, list)));
  }
 
  callback();
  return true;
};
 
/**
* Creates a anonymous function that check if the given uri is valid or not.
*
* @param {string} uri     The uri to validate.
* @return {boolean}
*/
exports.isValidUri = function (uri) {
  if (!check.isURL(uri)){
    throw new URIError('The provided URI "' + uri + '" is invalid.');
  }
  return true;
};
 
/**
* Checks if the given host is valid or not.
*
* @param {string|object} host     The host to validate.
* @return {boolean}
*/
exports.isValidHost= function (host) {
  if (azureutil.objectIsNull(host)) {
    throw new ArgumentNullError('host', SR.STORAGE_HOST_LOCATION_REQUIRED);
  } else {
    var storageHost = {};
    storageHost.primaryHost = _.isString(host) ? host : host.primaryHost;
    if (storageHost.primaryHost && !check.isURL(storageHost.primaryHost)){
      throw new URIError('The provided URI "' + storageHost.primaryHost + '" is invalid.');
    }
 
    storageHost.secondaryHost = _.isString(host) ? undefined : host.secondaryHost;
    if (storageHost.secondaryHost && !check.isURL(storageHost.secondaryHost)){
      throw new URIError('The provided URI "' + storageHost.secondaryHost + '" is invalid.');
    }
 
    if (!storageHost.primaryHost && !storageHost.secondaryHost) {
      throw new ArgumentNullError('host', SR.STORAGE_HOST_LOCATION_REQUIRED);
    }
  } 
 
  return true;
};
 
/**
* Checks if the given value is a valid UUID or not.
*
* @param {string|object} uuid     The uuid to validate.
* @return {boolean}
*/
exports.isValidUuid = function(uuid, callback) {
  var validUuidRegex = /^[a-zA-Z0-9]{8}\-[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{12}$/;
 
  var fail;
 
  initCallback(callback, function (f, cb) {
    fail = f;
    callback = cb;
  });
 
  if (!validUuidRegex.test(uuid)) {
    return fail(new SyntaxError('The value is not a valid UUID format.'));
  }
  
  callback();
  return true;
};
 
/**
* Creates a anonymous function that check if a given key is base 64 encoded.
*
* @param {string} key The key to validate.
* @return {function}
*/
exports.isBase64Encoded = function (key) {
  var isValidBase64String = key.match(/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/);
 
  if (isValidBase64String) {
    return true;
  } else {
    throw new SyntaxError('The provided account key ' + key + ' is not a valid base64 string.');
  }
};
 
/**
* Validates a function.
*
* @param {object} function The function to validate.
* @return {function}
*/
exports.isValidFunction = function (functionObject, functionName) {
  if (!functionObject) {
    throw new ArgumentNullError('functionObject', functionName + ' must be specified.');
  }
  if(!_.isFunction(functionObject)){
    throw new TypeError(functionName + ' specified should be a function.');
  }
  return true;
};
 
var getNameError = function(name, typeName) {
  // checks if name is null, undefined or empty
  if (azureutil.stringIsEmpty(name)) {
    return new ArgumentNullError('name', util.format('%s name must be a non empty string.', typeName));
  }
 
  // check if name is between 3 and 63 characters
  if (name.length < 3 || name.length > 63) {
    return new ArgumentError('name', util.format('%s name must be between 3 and 63 characters long.', typeName));
  }
 
  // check if name follows naming rules
  if (name.match(/^([a-z0-9]+(-[a-z0-9]+)*)$/) === null) {
    return new SyntaxError(util.format('%s name format is incorrect.', typeName));
  }
 
  return null;
};
 
/**
* Validates a container name.
*
* @param {string} containerName The container name.
*/
exports.containerNameIsValid = function (containerName, callback) {
  var fail;
  initCallback(callback, function (f, cb) {
    fail = f;
    callback = cb;
  });
 
  var nameError = getNameError(containerName, 'Container');
 
  if (!nameError || containerName.match(/^(\$root|\$logs)$/)) {
    callback();
    return true;
  } else {
    return fail(nameError);
  }
};
 
/**
* Validates a blob name.
*
* @param {string} containerName The container name.
* @param {string} blobname      The blob name.
*/
exports.blobNameIsValid = function (containerName, blobName, callback) {
  var fail;
  
  initCallback(callback, function (f, cb) {
    fail = f;
    callback = cb;
  });
  
  if (!blobName) {
    return fail(new ArgumentNullError('blobName', 'Blob name is not specified.'));
  }
  
  if (containerName === '$root' && blobName.indexOf('/') !== -1) {
    return fail(new SyntaxError('Blob name format is incorrect.'));
  }
  
  callback();
  return true;
};
 
/**
* Validates a share name.
*
* @param {string} shareName The share name.
*/
exports.shareNameIsValid = function (shareName, callback) {
  var fail;
  initCallback(callback, function (f, cb) {
    fail = f;
    callback = cb;
  });
 
  var nameError = getNameError(shareName, 'Share');
 
  if (!nameError) {
    callback();
    return true;
  } else {
    return fail(nameError);
  }
};
 
/**
* Validates a queue name.
*
* @param {string} queueName The queue name.
*/
exports.queueNameIsValid = function (queueName, callback) {
  var fail;
 
  initCallback(callback, function (f, cb) {
    fail = f;
    callback = cb;
  });
 
  var nameError = getNameError(queueName, 'Queue');
 
  if (!nameError) {
    callback();
    return true;
  } else {
    return fail(nameError);
  }
};
 
/**
* Validates a table name.
*
* @param {string} table  The table name.
*/
exports.tableNameIsValid = function (table, callback) {
  var fail;
 
  initCallback(callback, function (f, cb) {
    fail = f;
    callback = cb;
  });
 
  if (azureutil.stringIsEmpty(table)) {
    return fail(new ArgumentNullError('table', 'Table name must be a non empty string.'));
  }
 
  if (table.length < 3 || table.length > 63) {
    return fail(new ArgumentError('table', 'Table name must be between 3 and 63 characters long.'));
  }
 
  if(table.toLowerCase() == 'tables') {
    return fail(new RangeError('Table name cannot be \'Tables\'.'));
  }
 
  if (table.match(/^([A-Za-z][A-Za-z0-9]{2,62})$/) !== null || table === '$MetricsCapacityBlob' || table.match(/^(\$Metrics(HourPrimary|MinutePrimary|HourSecondary|MinuteSecondary)?(Transactions)(Blob|Queue|Table))$/) !== null) 
  {
    callback();
    return true;
  } else {
    return fail(new SyntaxError('Table name format is incorrect.'));
  }
};
 
/**
* Validates page ranges.
*
* @param {int} rangeStart             The range starting position.
* @param {int} rangeEnd               The range ending position.
* @param {int} writeBlockSizeInBytes  The block size.
*/
exports.pageRangesAreValid = function (rangeStart, rangeEnd, writeBlockSizeInBytes, callback) {
  var fail;
 
  initCallback(callback, function (f, cb) {
    fail = f;
    callback = cb;
  });
 
  if (rangeStart % 512 !== 0) {
    return fail(new RangeError('Start byte offset must be a multiple of 512.'));
  }
 
  var size = null;
  if (!azureutil.objectIsNull(rangeEnd)) {
    if ((rangeEnd + 1) % 512 !== 0) {
      return fail(new RangeError('End byte offset must be a multiple of 512 minus 1.'));
    }
 
    size = (rangeEnd - rangeStart) + 1;
    if (size > writeBlockSizeInBytes) {
      return fail(new RangeError('Page blob size cannot be larger than ' + writeBlockSizeInBytes + ' bytes.'));
    }
  }
  
  callback();
  return true;
};
 
/**
* Validates a blob type.
*
* @param {string} type  The type name.
*/
exports.blobTypeIsValid = function (type, callback) {
  var getEnumValues = function (obj) {
    var values = [];
    for (var prop in obj) {
      if (obj.hasOwnProperty(prop)) {
        values.push(obj[prop]);
      }
    }
    return values;
  };
  
  return this.isValidEnumValue(type, getEnumValues(blobConstants.BlobTypes), callback);
};
 
/**
* Validates share ACL type.
*
* @param {string} type  The type name.
*/
exports.shareACLIsValid = function (type, callback) {
  var fail;
  
  initCallback(callback, function (f, cb) {
    fail = f;
    callback = cb;
  });
  
  if (type != FileUtilities.SharePublicAccessType.OFF) {
    fail(new ArgumentError('type', 'The access type is not supported.'));
  }
 
  callback();
  return true;
};
 
/**
* Validates share quota value.
*
* @param {int} type  The quota value.
*/
exports.shareQuotaIsValid = function (quota, callback) {
  var fail;
  
  initCallback(callback, function (f, cb) {
    fail = f;
    callback = cb;
  });
  
  if (quota && quota <= 0) {
    fail(new RangeError('The share quota value, in GB, must be greater than 0.'));
  }
  
  callback();
  return true;
};
 
// common functions for validating arguments
 
function throwMissingArgument(name, func) {
  throw new ArgumentNullError(name, 'Required argument ' + name + ' for function ' + func + ' is not defined');
}
 
function ArgumentValidator(functionName) {
  this.func = functionName;
}
 
_.extend(ArgumentValidator.prototype, {
  string: function (val, name) {
    this.exists(val, name);
    if (typeof val !== 'string') {
      throw new TypeError('Parameter ' + name + ' for function ' + this.func + ' should be a non-empty string');
    }
  },
 
  stringAllowEmpty: function (val, name) {
    if (typeof val !== 'string') {
      throw new TypeError('Parameter ' + name + ' for function ' + this.func + ' should be a string');
    }
  },
 
  object: function (val, name) {
    this.exists(val, name);
    if (typeof val !== 'object') {
      throw new TypeError('Parameter ' + name + ' for function ' + this.func + ' should be an object');
    }
  },
 
  exists: function (val, name) {
    if (!val) {
      throwMissingArgument(name, this.func);
    }
  },
 
  function: function (val, name) {
    this.exists(val, name);
    if (typeof val !== 'function') {
      throw new TypeError('Parameter ' + name + ' for function ' + this.func + ' should be a function');
    }
  },
 
  value: function (val, name) {
    if (!val && val !== 0) {
      throwMissingArgument(name, this.func);
    }
  },
 
  nonEmptyArray: function (val, name) {
    if (!val || val.length === 0) {
      throw new TypeError('Required array argument ' + name + ' for function ' + this.func + ' is either not defined or empty');
    }
  },
 
  callback: function (val) {
    this.exists(val, 'callback');
    this.function(val, 'callback');
  },
 
  test: function (predicate, message) {
    if (!predicate()) {
      throw new Error(message + ' in function ' + this.func);
    }
  },
 
  tableNameIsValid: exports.tableNameIsValid,
  containerNameIsValid: exports.containerNameIsValid,
  shareNameIsValid: exports.shareNameIsValid,
  blobNameIsValid: exports.blobNameIsValid,
  pageRangesAreValid: exports.pageRangesAreValid,
  queueNameIsValid: exports.queueNameIsValid,
  blobTypeIsValid: exports.blobTypeIsValid,
  shareACLIsValid: exports.shareACLIsValid,
  shareQuotaIsValid: exports.shareQuotaIsValid,
  isValidEnumValue: exports.isValidEnumValue
});
 
function validateArgs(functionName, validationRules) {
  var validator = new ArgumentValidator(functionName);
  validationRules(validator);
}
 
exports.ArgumentValidator = ArgumentValidator;
exports.validateArgs = validateArgs;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/

Statements: 7.47% (142 / 1901)      Branches: 0% (0 / 614)      Functions: 0% (0 / 345)      Lines: 7.98% (142 / 1779)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/
File Statements Branches Functions Lines
blobservice.js 7.32% (139 / 1898) 0% (0 / 614) 0% (0 / 345) 7.83% (139 / 1776)
blobutilities.js 100% (3 / 3) 100% (0 / 0) 100% (0 / 0) 100% (3 / 3)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/blobservice.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/blobservice.js

Statements: 7.32% (139 / 1898)      Branches: 0% (0 / 614)      Functions: 0% (0 / 345)      Lines: 7.83% (139 / 1776)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998                                  1 1 1 1 1 1 1   1 1 1 1 1 1 1 1 1 1     1 1 1 1 1     1 1 1 1 1 1     1 1 1 1 1 1   1     1 1 1 1                                                                 1                           1                       1                                                                           1                                                                                                   1                                                 1                                                       1                                                         1                                                                                                                                                                                   1                                                                             1                                                                                                                                               1                                                                                                                           1                                                                                                                     1                                                                                                                             1                                                                                                                   1                                                                                                                     1                                                                                                                                             1                                                                                                     1                                                                                                                     1                                                       1                                                                     1                                                               1                                                             1                                                                                   1                                                                               1                                                                               1                                                                                 1                                                                                       1                                                                                                                                         1                                                                                                                                                 1                                                                                                           1                                                                                                                                                                     1                                                                                                 1                                                                                                                                       1                                                                                                                                                                     1                                                                                                                                                     1                                                                                                                   1                                                                                             1                                                                                                                             1                                                                                                                               1                                                                                                                                                                   1                                                                                                           1                                                                                                                                           1                                                                                                                             1                                                                                                                                                                 1                                                                                           1                                                                                                   1                                                                                                   1                                                                 1                                                                                                             1                                                                                                                                                                                       1                                                                                                                                                                                                                               1                                                                                                     1                                                                                                                     1                                                                                                                                                                                     1                                                                                             1                                                                                 1                                                                                                 1                                                               1                                                                                                 1                                                                                                     1                                                                                                                                                             1                                                                                                                                 1                                                                             1               1                                                                           1                                                                                                                                                     1                                                                                             1                                                                                       1                                                                                         1                                                                                         1                                                                                   1                                                                                                                                                 1                                                                                                           1                                                                         1                                                                                                       1                                                                                                                                 1                                                                                                                                                                                             1                                                                                                                                             1                                                                                                                                               1                                                                                                                                                                                                         1                                                                                                                                                                                                                                     1                                                                                                                                                                                                                       1                                                                                                                                                                   1                                                                                                                                                                                 1                                                                                                                                     1                                                                 1                                                                                                                                                           1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   1                                                                                                               1                                                                   1                                         1                                                                                             1                                                                                               1                                                                                                                                                                                                                                                                                                                                                                                                                   1                                                                                                                                               1                                                                                                             1                                                                                                                                                                               1                                             1   1    
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var fs = require('fs');
var qs = require('querystring');
var url = require('url');
var util = require('util');
var mime = require('browserify-mime');
var _ = require('underscore');
var extend = require('extend');
 
var azureCommon = require('./../../common/common');
var BlockRangeStream = require('./internal/blockrangestream');
var Md5Wrapper = require('./../../common/md5-wrapper');
var PageRangeStream = require('./internal/pagerangestream');
var RangeStream = require('./../../common/streams/rangestream');
var azureutil = azureCommon.util;
var SR = azureCommon.SR;
var validate = azureCommon.validate;
var StorageServiceClient = azureCommon.StorageServiceClient;
var WebResource = azureCommon.WebResource;
 
// Constants
var Constants = azureCommon.Constants;
var BlobConstants = Constants.BlobConstants;
var HeaderConstants = Constants.HeaderConstants;
var QueryStringConstants = Constants.QueryStringConstants;
var RequestLocationMode = Constants.RequestLocationMode;
 
// Streams
var BatchOperation = azureCommon.BatchOperation;
var SpeedSummary = azureCommon.SpeedSummary;
var ChunkAllocator = azureCommon.ChunkAllocator;
var ChunkStream = azureCommon.ChunkStream;
var ChunkStreamWithStream = azureCommon.ChunkStreamWithStream;
var FileReadStream = azureCommon.FileReadStream;
 
// Models requires
var AclResult = azureCommon.AclResult;
var ServiceStatsParser = azureCommon.ServiceStatsParser;
var BlockListResult = require('./models/blocklistresult');
var BlobResult = require('./models/blobresult');
var ContainerResult = require('./models/containerresult');
var LeaseResult = require('./models/leaseresult');
 
var BlobUtilities = require('./blobutilities');
 
// Errors requires
var errors = require('../../common/errors/errors');
var ArgumentError = errors.ArgumentError;
var ArgumentNullError = errors.ArgumentNullError;
var StorageError = errors.StorageError;
 
/**
* Creates a new BlobService object.
* If no connection string or storageaccount and storageaccesskey are provided,
* the AZURE_STORAGE_CONNECTION_STRING or AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables will be used.
* @class
* The BlobService class is used to perform operations on the Microsoft Azure Blob Service.
* The Blob Service provides storage for binary large objects, and provides
* functions for working with data stored in blobs as either streams or pages of data.
* 
* For more information on the Blob Service, as well as task focused information on using it in a Node.js application, see
* [How to Use the Blob Service from Node.js](http://azure.microsoft.com/en-us/documentation/articles/storage-nodejs-how-to-use-blob-storage/).
* The following defaults can be set on the blob service.
* singleBlobPutThresholdInBytes                       The default maximum size, in bytes, of a blob before it must be separated into blocks.
* defaultTimeoutIntervalInMs                          The default timeout interval, in milliseconds, to use for request made via the Blob service.
* defaultClientRequestTimeoutInMs                     The default timeout of client requests, in milliseconds, to use for the request made via the Blob service.
* defaultMaximumExecutionTimeInMs                     The default maximum execution time across all potential retries, for requests made via the Blob service.
* defaultLocationMode                                 The default location mode for requests made via the Blob service.
* parallelOperationThreadCount                        The number of parallel operations that may be performed when uploading a blob that is greater than 
*                                                     the value specified by the singleBlobPutThresholdInBytes property in size.
* useNagleAlgorithm                                   Determines whether the Nagle algorithm is used for requests made via the Blob service; true to use the  
*                                                     Nagle algorithm; otherwise, false. The default value is false.
* @constructor
* @extends {StorageServiceClient}
*
* @param {string} [storageAccountOrConnectionString]  The storage account or the connection string.
* @param {string} [storageAccessKey]                  The storage access key.
* @param {string|object} [host]                       The host address. To define primary only, pass a string. 
*                                                     Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host.
* @param {string} [sasToken]                          The Shared Access Signature token.
* @param {string} [endpointSuffix]                    The endpoint suffix.
*/
function BlobService(storageAccountOrConnectionString, storageAccessKey, host, sasToken, endpointSuffix) {
  var storageServiceSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey, host, sasToken, endpointSuffix);
 
  BlobService['super_'].call(this,
    storageServiceSettings._name,
    storageServiceSettings._key,
    storageServiceSettings._blobEndpoint,
    storageServiceSettings._usePathStyleUri,
    storageServiceSettings._sasToken);
 
  this.singleBlobPutThresholdInBytes = BlobConstants.DEFAULT_SINGLE_BLOB_PUT_THRESHOLD_IN_BYTES;
  this.parallelOperationThreadCount = Constants.DEFAULT_PARALLEL_OPERATION_THREAD_COUNT;
}
 
util.inherits(BlobService, StorageServiceClient);
 
// Non-class methods
 
/**
* Create resource name
* @ignore
*
* @param {string} containerName Container name
* @param {string} blobName      Blob name
* @return {string} The encoded resource name.
*/
function createResourceName(containerName, blobName, forSAS) {
  // Resource name
  if (blobName && !forSAS) {
    blobName = encodeURIComponent(blobName);
    blobName = blobName.replace(/%2F/g, '/');
    blobName = blobName.replace(/%5C/g, '/');
    blobName = blobName.replace(/\+/g, '%20');
  }
 
  // return URI encoded resource name
  if (blobName) {
    return containerName + '/' + blobName;
  }
  else {
    return containerName;
  }
}
 
// Blob service methods
 
/**
* Gets the service stats for a storage account’s Blob service.
*
* @this {BlobService}
* @param {object}       [options]                               The request options.
* @param {LocationMode} [options.locationMode]                  Specifies the location mode used to decide which location the request should be sent to. 
*                                                               Please see StorageUtilities.LocationMode for the possible values.
* @param {int}          [options.timeoutIntervalInMs]           The timeout interval, in milliseconds, to use for the request.
* @param {int}          [options.clientRequestTimeoutInMs]      The timeout of client requests, in milliseconds, to use for the request.
* @param {int}          [options.maximumExecutionTimeInMs]      The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                               The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                               execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}       [options.clientRequestId]               A string that represents the client request ID with a 1KB character limit.
* @param {bool}         [options.useNagleAlgorithm]             Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                               The default value is false.
* @param {errorOrResult}  callback                              `error` will contain information if an error occurs; otherwise, `[result]{@link ServiceStats}` will contain the stats and 
*                                                               `response` will contain information related to this operation.
*/
BlobService.prototype.getServiceStats = function (optionsOrCallback, callback) {
  var options;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; });
 
  validate.validateArgs('getServiceStats', function (v) {
    v.callback(callback);
  });
 
  var webResource = WebResource.get()
    .withQueryOption(QueryStringConstants.COMP, 'stats')
    .withQueryOption(QueryStringConstants.RESTYPE, 'service');
 
  options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY;
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.serviceStatsResult = null;
    if (!responseObject.error) {
      responseObject.serviceStatsResult = ServiceStatsParser.parse(responseObject.response.body.StorageServiceStats);
    }
 
    // function to be called after all filters
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.serviceStatsResult, returnObject.response);
    };
 
    // call the first filter
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Gets the properties of a storage account’s Blob service, including Azure Storage Analytics.
*
* @this {BlobService}
* @param {object}       [options]                               The request options.
* @param {LocationMode} [options.locationMode]                  Specifies the location mode used to decide which location the request should be sent to. 
*                                                               Please see StorageUtilities.LocationMode for the possible values.
* @param {int}          [options.timeoutIntervalInMs]           The server timeout interval, in milliseconds, to use for the request.
* @param {int}          [options.clientRequestTimeoutInMs]      The timeout of client requests, in milliseconds, to use for the request.
* @param {int}          [options.maximumExecutionTimeInMs]      The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                               The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                               execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}       [options.clientRequestId]               A string that represents the client request ID with a 1KB character limit.
* @param {bool}         [options.useNagleAlgorithm]             Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                               The default value is false.
* @param {errorOrResult}  callback                              `error` will contain information if an error occurs; otherwise, `[result]{@link ServiceProperties}` will contain the properties 
*                                                               and `response` will contain information related to this operation.
*/
BlobService.prototype.getServiceProperties = function (optionsOrCallback, callback) {
  return this.getAccountServiceProperties(optionsOrCallback, callback);
};
 
/**
* Sets the properties of a storage account’s Blob service, including Azure Storage Analytics.
* You can also use this operation to set the default request version for all incoming requests that do not have a version specified.
*
* @this {BlobService}
* @param {object}             serviceProperties                        The service properties.
* @param {object}             [options]                                The request options.
* @param {LocationMode}       [options.locationMode]                   Specifies the location mode used to decide which location the request should be sent to. 
*                                                                      Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]            The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]       The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]       The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                      The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                      execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]              Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                      The default value is false.
* @param {errorOrResponse}    callback                                 `error` will contain information
*                                                                      if an error occurs; otherwise, `response`
*                                                                      will contain information related to this operation.
*/
BlobService.prototype.setServiceProperties = function (serviceProperties, optionsOrCallback, callback) {
  return this.setAccountServiceProperties(serviceProperties, optionsOrCallback, callback);
};
 
/**
* Lists a segment containing a collection of container items under the specified account.
*
* @this {BlobService}
* @param {object}             currentToken                                A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {object}             [options]                                   The request options.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.maxResults]                        Specifies the maximum number of containers to return per call to Azure storage.
* @param {string}             [options.include]                           Include this parameter to specify that the container's metadata be returned as part of the response body. (allowed values: '', 'metadata')
*                                                                         **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. 
*                                                                         `entries`  gives a list of `[containers]{@link ContainerResult}` and the `continuationToken` is used for the next listing operation.
*                                                                         `response` will contain information related to this operation.
*/
BlobService.prototype.listContainersSegmented = function (currentToken, optionsOrCallback, callback) {
  this.listContainersSegmentedWithPrefix(null /* prefix */, currentToken, optionsOrCallback, callback);
};
 
/**
* Lists a segment containing a collection of container items whose names begin with the specified prefix under the specified account.
*
* @this {BlobService}
* @param {string}             prefix                                      The prefix of the container name.
* @param {object}             currentToken                                A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {object}             [options]                                   The request options.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.maxResults]                        Specifies the maximum number of containers to return per call to Azure storage.
* @param {string}             [options.include]                           Include this parameter to specify that the container's metadata be returned as part of the response body. (allowed values: '', 'metadata')
*                                                                         **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. 
*                                                                         `entries`  gives a list of `[containers]{@link ContainerResult}` and the `continuationToken` is used for the next listing operation.
*                                                                         `response` will contain information related to this operation.
*/
BlobService.prototype.listContainersSegmentedWithPrefix = function (prefix, currentToken, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('listContainers', function (v) {
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.get()
    .withQueryOption(QueryStringConstants.COMP, 'list')
    .withQueryOption(QueryStringConstants.MAX_RESULTS, options.maxResults)
    .withQueryOption(QueryStringConstants.INCLUDE, options.include);
 
  if (!azureutil.objectIsNull(currentToken)) {
    webResource.withQueryOption(QueryStringConstants.MARKER, currentToken.nextMarker);
  }
 
  webResource.withQueryOption(QueryStringConstants.PREFIX, prefix);
 
  options.requestLocationMode = azureutil.getNextListingLocationMode(currentToken);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.listContainersResult = null;
 
    if (!responseObject.error) {
      responseObject.listContainersResult = {
        entries: null,
        continuationToken: null
      };
      responseObject.listContainersResult.entries = [];
 
      var containers = [];
 
      if (responseObject.response.body.EnumerationResults.Containers && responseObject.response.body.EnumerationResults.Containers.Container) {
        containers = responseObject.response.body.EnumerationResults.Containers.Container;
        if (!_.isArray(containers)) {
          containers = [ containers ];
        }
      }
 
      containers.forEach(function (currentContainer) {
        var containerResult = ContainerResult.parse(currentContainer);
        responseObject.listContainersResult.entries.push(containerResult);
      });
 
      if (responseObject.response.body.EnumerationResults.NextMarker) {
        responseObject.listContainersResult.continuationToken = {
          nextMarker: null,
          targetLocation: null
        };
 
        responseObject.listContainersResult.continuationToken.nextMarker = responseObject.response.body.EnumerationResults.NextMarker;
        responseObject.listContainersResult.continuationToken.targetLocation = responseObject.targetLocation;
      }
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.listContainersResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
// Container methods
 
/**
* Checks whether or not a container exists on the service.
*
* @this {BlobService}
* @param {string}             container                               The container name.
* @param {object}             [options]                               The request options.
* @param {LocationMode}       [options.locationMode]                  Specifies the location mode used to decide which location the request should be sent to. 
*                                                                     Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]           The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]      The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                     The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                     execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]               A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]             Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                     The default value is false.
* @param {errorOrResult}      callback                                `error` will contain information
*                                                                     if an error occurs; otherwise `[result]{@link ContainerResult}` will contain
*                                                                     the container information including `exists` boolean member. 
*                                                                     `response` will contain information related to this operation.
*/
BlobService.prototype.doesContainerExist = function (container, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('doesContainerExist', function (v) {
    v.string(container, 'container');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
 
  this._doesContainerExist(container, false, options, callback);
};
 
/**
* Creates a new container under the specified account.
* If a container with the same name already exists, the operation fails.
*
* @this {BlobService}
* @param {string}             container                           The container name.
* @param {object}             [options]                           The request options.
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {object}             [options.metadata]                  The metadata key/value pairs.
* @param {string}             [options.publicAccessLevel]         Specifies whether data in the container may be accessed publicly and the level of access.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise `[result]{@link ContainerResult}` will contain
*                                                                 the container information.
*                                                                 `response` will contain information related to this operation.
*/
BlobService.prototype.createContainer = function (container, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('createContainer', function (v) {
    v.string(container, 'container');
    v.test(function () { return container !== '$logs'; },
      'Container name format is incorrect');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.put(container)
    .withQueryOption(QueryStringConstants.RESTYPE, 'container');
 
  webResource.addOptionalMetadataHeaders(options.metadata);
  webResource.withHeader(HeaderConstants.BLOB_PUBLIC_ACCESS, options.publicAccessLevel);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.containerResult = null;
    if (!responseObject.error) {
      responseObject.containerResult = new ContainerResult(container);
      responseObject.containerResult.getPropertiesFromHeaders(responseObject.response.headers);
 
      if (options.metadata) {
        responseObject.containerResult.metadata = options.metadata;
      }
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.containerResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Creates a new container under the specified account if the container does not exists.
*
* @this {BlobService}
* @param {string}             container                                 The container name.
* @param {object}             [options]                                 The request options.
* @param {LocationMode}       [options.locationMode]                    Specifies the location mode used to decide which location the request should be sent to. 
*                                                                       Please see StorageUtilities.LocationMode for the possible values.
* @param {object}             [options.metadata]                        The metadata key/value pairs.
* @param {string}             [options.publicAccessLevel]               Specifies whether data in the container may be accessed publicly and the level of access.
* @param {int}                [options.timeoutIntervalInMs]             The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]        The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]        The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                       The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                       execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                 A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]               Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                       The default value is false.
* @param {errorOrResult}      callback                                  `error` will contain information
*                                                                       if an error occurs; otherwise `[result]{@link ContainerResult}` will contain
*                                                                       the container information including `created` boolean member. 
*                                                                       `response` will contain information related to this operation.
*
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
* blobService.createContainerIfNotExists('taskcontainer', {publicAccessLevel : 'blob'}, function(error) {
*   if(!error) {
*     // Container created or exists, and is public
*   }
* }); 
*/
BlobService.prototype.createContainerIfNotExists = function (container, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('createContainerIfNotExists', function (v) {
    v.string(container, 'container');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var self = this;
  self._doesContainerExist(container, true, options, function (error, result, response) {
    var exists = result.exists;
    result.created = false;
    delete result.exists;
    
    if (error) {
      callback(error, result, response);
    } else if (exists) {
      response.isSuccessful = true;
      callback(error, result, response);
    } else {
      self.createContainer(container, options, function (createError, containerResult, createResponse) {
        if (!createError) {
          containerResult.created = true;
        }
        else if (createError && createError.statusCode === Constants.HttpConstants.HttpResponseCodes.Conflict && createError.code === Constants.BlobErrorCodeStrings.CONTAINER_ALREADY_EXISTS) {
          // If it was created before, there was no actual error.
          createError = null;
          createResponse.isSuccessful = true;
        }
 
        callback(createError, containerResult, createResponse);
      });
    }
  });
};
 
/**
* Retrieves a container and its properties from a specified account.
* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive.
*
* @this {BlobService}
* @param {string}             container                           The container name.
* @param {object}             [options]                           The request options.
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {string}             [options.leaseId]                   The container lease identifier.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise `[result]{@link ContainerResult}` will contain
*                                                                 information for the container.
*                                                                 `response` will contain information related to this operation.
*/
BlobService.prototype.getContainerProperties = function (container, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('getContainerProperties', function (v) {
    v.string(container, 'container');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.head(container)
    .withQueryOption(QueryStringConstants.RESTYPE, 'container')
    .withHeader(HeaderConstants.LEASE_ID, options.leaseId);
 
  options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
 
  var self = this;
  var processResponseCallback = function (responseObject, next) {
    responseObject.containerResult = null;
    if (!responseObject.error) {
      responseObject.containerResult = new ContainerResult(container);
      responseObject.containerResult.metadata = self.parseMetadataHeaders(responseObject.response.headers);
      responseObject.containerResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.containerResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Returns all user-defined metadata for the container.
* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive.
*
* @this {BlobService}
* @param {string}             container                                 The container name.
* @param {object}             [options]                                 The request options.
* @param {string}             [options.leaseId]                         The container lease identifier.
* @param {LocationMode}       [options.locationMode]                    Specifies the location mode used to decide which location the request should be sent to. 
*                                                                       Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]             The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]        The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]        The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                       The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                       execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                 A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]               Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                       The default value is false.
* @param {errorOrResult}      callback                                  `error` will contain information
*                                                                       if an error occurs; otherwise `[result]{@link ContainerResult}` will contain
*                                                                       information for the container.
*                                                                       `response` will contain information related to this operation.
*/
BlobService.prototype.getContainerMetadata = function (container, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('getContainerMetadata', function (v) {
    v.string(container, 'container');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.head(container)
    .withQueryOption(QueryStringConstants.RESTYPE, 'container')
    .withQueryOption(QueryStringConstants.COMP, 'metadata')
    .withHeader(HeaderConstants.LEASE_ID, options.leaseId);
 
  options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
 
  var self = this;
  var processResponseCallback = function (responseObject, next) {
    responseObject.containerResult = null;
    if (!responseObject.error) {
      responseObject.containerResult = new ContainerResult(container);
      responseObject.containerResult.metadata = self.parseMetadataHeaders(responseObject.response.headers);
      responseObject.containerResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.containerResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Sets the container's metadata.
*
* Calling the Set Container Metadata operation overwrites all existing metadata that is associated with the container.
* It's not possible to modify an individual name/value pair.
*
* @this {BlobService}
* @param {string}             container                           The container name.
* @param {object}             metadata                            The metadata key/value pairs.
* @param {object}             [options]                           The request options.
* @param {string}             [options.leaseId]                   The container lease identifier.
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {AccessConditions}   [options.accessConditions]          The access conditions.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResponse}    callback                            `error` will contain information
*                                                                 if an error occurs; otherwise 
*                                                                 `response` will contain information related to this operation.
*/
BlobService.prototype.setContainerMetadata = function (container, metadata, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('setContainerMetadata', function (v) {
    v.string(container, 'container');
    v.object(metadata, 'metadata');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.put(container)
    .withQueryOption(QueryStringConstants.RESTYPE, 'container')
    .withQueryOption(QueryStringConstants.COMP, 'metadata')
    .withHeader(HeaderConstants.LEASE_ID, options.leaseId);
 
  webResource.addOptionalMetadataHeaders(metadata);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.containerResult = null;
    if (!responseObject.error) {
      responseObject.containerResult = new ContainerResult(container);
      responseObject.containerResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.containerResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Gets the container's ACL.
*
* @this {BlobService}
* @param {string}             container                           The container name.
* @param {object}             [options]                           The request options.
* @param {string}             [options.leaseId]                   The container lease identifier.
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise `[result]{@link ContainerAclResult}` will contain
*                                                                 information for the container.
*                                                                 `response` will contain information related to this operation.
*/
BlobService.prototype.getContainerAcl = function (container, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('getContainerAcl', function (v) {
    v.string(container, 'container');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.get(container)
    .withQueryOption(QueryStringConstants.RESTYPE, 'container')
    .withQueryOption(QueryStringConstants.COMP, 'acl')
    .withHeader(HeaderConstants.LEASE_ID, options.leaseId);
 
  options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.containerResult = null;
    if (!responseObject.error) {
      responseObject.containerResult = new ContainerResult(container);
      responseObject.containerResult.getPropertiesFromHeaders(responseObject.response.headers);
      responseObject.containerResult.signedIdentifiers = AclResult.parse(responseObject.response.body);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.containerResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Updates the container's ACL.
*
* @this {BlobService}
* @param {string}                         container                           The container name.
* @param {Object.<string, AccessPolicy>}  signedIdentifiers                   The container ACL settings. See `[AccessPolicy]{@link AccessPolicy}` for detailed information.
* @param {object}                         [options]                           The request options.
* @param {AccessConditions}               [options.accessConditions]          The access conditions.
* @param {string}                         [options.publicAccessLevel]         Specifies whether data in the container may be accessed publicly and the level of access.
* @param {string}                         [options.leaseId]                   The container lease identifier.
* @param {int}                            [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                            [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                            [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                             The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                             execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}                         [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}                           [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                             The default value is false.
* @param {errorOrResult}                  callback                            `error` will contain information
*                                                                             if an error occurs; otherwise `[result]{@link ContainerAclResult}` will contain
*                                                                             information for the container.
*                                                                             `response` will contain information related to this operation.
*/
BlobService.prototype.setContainerAcl = function (container, signedIdentifiers, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('setContainerAcl', function (v) {
    v.string(container, 'container');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
 
  var policies = null;
  if (signedIdentifiers) {
    if(_.isArray(signedIdentifiers)) {
      throw new TypeError(SR.INVALID_SIGNED_IDENTIFIERS);
    }
    policies = AclResult.serialize(signedIdentifiers);
  }
 
  var webResource = WebResource.put(container)
    .withQueryOption(QueryStringConstants.RESTYPE, 'container')
    .withQueryOption(QueryStringConstants.COMP, 'acl')
    .withHeader(HeaderConstants.CONTENT_LENGTH, !azureutil.objectIsNull(policies) ? Buffer.byteLength(policies) : 0)
    .withHeader(HeaderConstants.BLOB_PUBLIC_ACCESS, options.publicAccessLevel)
    .withHeader(HeaderConstants.LEASE_ID, options.leaseId)
    .withBody(policies);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.containerResult = null;
    if (!responseObject.error) {
      responseObject.containerResult = new ContainerResult(container, options.publicAccessLevel);
      responseObject.containerResult.getPropertiesFromHeaders(responseObject.response.headers);
      if (signedIdentifiers) {
        responseObject.containerResult.signedIdentifiers = signedIdentifiers;
      }
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.containerResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, webResource.body, options, processResponseCallback);
};
 
/**
* Marks the specified container for deletion.
* The container and any blobs contained within it are later deleted during garbage collection.
*
* @this {BlobService}
* @param {string}             container                           The container name.
* @param {object}             [options]                           The request options.
* @param {AccessConditions}   [options.accessConditions]          The access conditions.
* @param {string}             [options.leaseId]                   The container lease identifier.
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResponse}    callback                            `error` will contain information
*                                                                 if an error occurs; otherwise
*                                                                 `response` will contain information related to this operation.
*/
BlobService.prototype.deleteContainer = function (container, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('deleteContainer', function (v) {
    v.string(container, 'container');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.del(container)
    .withQueryOption(QueryStringConstants.RESTYPE, 'container')
    .withHeader(HeaderConstants.LEASE_ID, options.leaseId);
  
  var processResponseCallback = function (responseObject, next) {
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Marks the specified container for deletion if it exists.
* The container and any blobs contained within it are later deleted during garbage collection.
*
* @this {BlobService}
* @param {string}             container                           The container name.
* @param {object}             [options]                           The request options.
* @param {AccessConditions}   [options.accessConditions]          The access conditions.
* @param {string}             [options.leaseId]                   The container lease identifier.
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise `result` will 
*                                                                 be true if the container exists and was deleted, or false if the container
*                                                                 did not exist.
*                                                                 `response` will contain information related to this operation.
*/
BlobService.prototype.deleteContainerIfExists = function (container, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('deleteContainerIfExists', function (v) {
    v.string(container, 'container');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var self = this;
  self._doesContainerExist(container, true, options, function (error, result, response) {
    if (error) {
      callback(error, result.exists, response);
    } else if (!result.exists) {
      response.isSuccessful = true;
      callback(error, false, response);
    } else {
      self.deleteContainer(container, options, function (deleteError, deleteResponse) {
        var deleted;
        if (!deleteError) {
          deleted = true;
        } else if (deleteError && deleteError.statuscode === Constants.HttpConstants.HttpResponseCodes.NotFound && deleteError.code === Constants.BlobErrorCodeStrings.CONTAINER_NOT_FOUND) {
          // If it was deleted already, there was no actual error.
          deleted = false;
          deleteError = null;
          deleteResponse.isSuccessful = true;
        }
 
        callback(deleteError, deleted, deleteResponse);
      });
    }
  });
};
 
/**
* Lists a segment containing a collection of blob directory items in the container.
*
* @this {BlobService}
* @param {string}             container                           The container name.
* @param {object}             currentToken                        A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {object}             [options]                           The request options.
* @param {int}                [options.maxResults]                Specifies the maximum number of directories to return per call to Azure ServiceClient. This does NOT affect list size returned by this function. (maximum: 5000)
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. 
*                                                                 `entries`  gives a list of `[directories]{@link DirectoryResult}` and the `continuationToken` is used for the next listing operation.
*                                                                 `response` will contain information related to this operation.
*/
BlobService.prototype.listBlobDirectoriesSegmented = function (container, currentToken, optionsOrCallback, callback) {
  this.listBlobDirectoriesSegmentedWithPrefix(container, null /* prefix */, currentToken, optionsOrCallback, callback);
};
 
/**
* Lists a segment containing a collection of blob directory items in the container.
*
* @this {BlobService}
* @param {string}             container                           The container name.
* @param {string}             prefix                              The prefix of the blob directory.
* @param {object}             currentToken                        A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {object}             [options]                           The request options.
* @param {int}                [options.maxResults]                Specifies the maximum number of directories to return per call to Azure ServiceClient. This does NOT affect list size returned by this function. (maximum: 5000)
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. 
*                                                                 `entries`  gives a list of `[directories]{@link BlobResult}` and the `continuationToken` is used for the next listing operation.
*                                                                 `response` will contain information related to this operation.
*/
BlobService.prototype.listBlobDirectoriesSegmentedWithPrefix = function (container, prefix, currentToken, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  userOptions.delimiter = '/';
 
  this._listBlobsOrDircotriesSegmentedWithPrefix(container, prefix, currentToken, BlobConstants.ListBlobTypes.Directory, userOptions, callback);
};
 
/**
* Lists a segment containing a collection of blob items in the container.
*
* @this {BlobService}
* @param {string}             container                           The container name.
* @param {object}             currentToken                        A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {object}             [options]                           The request options.
* @param {string}             [options.delimiter]                 Delimiter, i.e. '/', for specifying folder hierarchy.
* @param {int}                [options.maxResults]                Specifies the maximum number of blobs to return per call to Azure ServiceClient. This does NOT affect list size returned by this function. (maximum: 5000)
* @param {string}             [options.include]                   Specifies that the response should include one or more of the following subsets: '', 'metadata', 'snapshots', 'uncommittedblobs', 'copy'). 
*                                                                 Please find these values in BlobUtilities.BlobListingDetails. Multiple values can be added separated with a comma (,).
*                                                                 **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive.
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. 
*                                                                 `entries`  gives a list of `[blobs]{@link BlobResult}` and the `continuationToken` is used for the next listing operation.
*                                                                 `response` will contain information related to this operation.
*/
BlobService.prototype.listBlobsSegmented = function (container, currentToken, optionsOrCallback, callback) {
  this.listBlobsSegmentedWithPrefix(container, null /* prefix */, currentToken, optionsOrCallback, callback);
};
 
/**
* Lists a segment containing a collection of blob items whose names begin with the specified prefix in the container.
*
* @this {BlobService}
* @param {string}             container                           The container name.
* @param {string}             prefix                              The prefix of the blob name.
* @param {object}             currentToken                        A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {object}             [options]                           The request options.
* @param {string}             [options.delimiter]                 Delimiter, i.e. '/', for specifying folder hierarchy.
* @param {int}                [options.maxResults]                Specifies the maximum number of blobs to return per call to Azure ServiceClient. This does NOT affect list size returned by this function. (maximum: 5000)
* @param {string}             [options.include]                   Specifies that the response should include one or more of the following subsets: '', 'metadata', 'snapshots', 'uncommittedblobs', 'copy').
*                                                                 Please find these values in BlobUtilities.BlobListingDetails. Multiple values can be added separated with a comma (,).
*                                                                 **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive.
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise `result` will contain
*                                                                 the entries of `[blobs]{@link BlobResult}` and the continuation token for the next listing operation.
*                                                                 `response` will contain information related to this operation.
*/
BlobService.prototype.listBlobsSegmentedWithPrefix = function (container, prefix, currentToken, optionsOrCallback, callback) {
  this._listBlobsOrDircotriesSegmentedWithPrefix(container, prefix, currentToken, BlobConstants.ListBlobTypes.Blob, optionsOrCallback, callback);
};
 
// Lease methods
 
/**
* Acquires a new lease. If container and blob are specified, acquires a blob lease. Otherwise, if only container is specified and blob is null, acquires a container lease.
*
* @this {BlobService}
* @param {string}             container                                   The container name.
* @param {string}             blob                                        The blob name.
* @param {object}             [options]                                   The request options.
* @param {string}             [options.leaseDuration]                     The lease duration in seconds. A non-infinite lease can be between 15 and 60 seconds. Default is never to expire. 
* @param {string}             [options.proposedLeaseId]                   The proposed lease identifier. Must be a GUID.
* @param {AccessConditions}   [options.accessConditions]                  The access conditions.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link LeaseResult}` will contain
*                                                                         the lease information.
*                                                                         `response` will contain information related to this operation.
*/
BlobService.prototype.acquireLease = function (container, blob, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('acquireLease', function (v) {
    v.string(container, 'container');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
 
  if (!options.leaseDuration) {
    options.leaseDuration = -1;
  }
 
  this._leaseImpl(container, blob, null /* leaseId */, BlobConstants.LeaseOperation.ACQUIRE, options, callback);
};
 
/**
* Renews an existing lease. If container and blob are specified, renews the blob lease. Otherwise, if only container is specified and blob is null, renews the container lease.
*
* @this {BlobService}
* @param {string}             container                                   The container name.
* @param {string}             blob                                        The blob name.
* @param {string}             leaseId                                     The lease identifier. Must be a GUID.
* @param {object}             [options]                                   The request options.
* @param {AccessConditions}   [options.accessConditions]                  The access conditions.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link LeaseResult}` will contain
*                                                                         the lease information.
*                                                                         `response` will contain information related to this operation.
*/
BlobService.prototype.renewLease = function (container, blob, leaseId, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('renewLease', function (v) {
    v.string(container, 'container');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
 
  this._leaseImpl(container, blob, leaseId, BlobConstants.LeaseOperation.RENEW, options, callback);
};
 
/**
* Changes the lease ID of an active lease. If container and blob are specified, changes the blob lease. Otherwise, if only container is specified and blob is null, changes the 
* container lease.
*
* @this {BlobService}
* @param {string}             container                                   The container name.
* @param {string}             blob                                        The blob name.
* @param {string}             leaseId                                     The current lease identifier.
* @param {string}             proposedLeaseId                             The proposed lease identifier. Must be a GUID. 
* @param {object}             [options]                                   The request options.
* @param {AccessConditions}   [options.accessConditions]                  The access conditions.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information if an error occurs; 
*                                                                         otherwise `[result]{@link LeaseResult}` will contain  the lease information.
*                                                                         `response` will contain information related to this operation.
*/
BlobService.prototype.changeLease = function (container, blob, leaseId, proposedLeaseId, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('changeLease', function (v) {
    v.string(container, 'container');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
 
  options.proposedLeaseId = proposedLeaseId;
  this._leaseImpl(container, blob, leaseId, BlobConstants.LeaseOperation.CHANGE, options, callback);
};
 
/**
* Releases the lease. If container and blob are specified, releases the blob lease. Otherwise, if only container is specified and blob is null, releases the container lease.
*
* @this {BlobService}
* @param {string}             container                                   The container name.
* @param {string}             blob                                        The blob name.
* @param {string}             leaseId                                     The lease identifier.
* @param {object}             [options]                                   The request options.
* @param {AccessConditions}   [options.accessConditions]                  The access conditions.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link LeaseResult}` will contain
*                                                                         the lease information.
*                                                                         `response` will contain information related to this operation.
*/
BlobService.prototype.releaseLease = function (container, blob, leaseId, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('releaseLease', function (v) {
    v.string(container, 'container');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
 
  this._leaseImpl(container, blob, leaseId, BlobConstants.LeaseOperation.RELEASE, options, callback);
};
 
/**
* Breaks the lease but ensures that another client cannot acquire a new lease until the current lease period has expired. If container and blob are specified, breaks the blob lease. 
* Otherwise, if only container is specified and blob is null, breaks the container lease.
*
* @this {BlobService}
* @param {string}             container                                   The container name.
* @param {string}             blob                                        The blob name.
* @param {object}             [options]                                   The request options.
* @param {int}                [options.leaseBreakPeriod]                  The lease break period, between 0 and 60 seconds. If unspecified, a fixed-duration lease breaks after 
*                                                                         the remaining lease period elapses, and an infinite lease breaks immediately.
* @param {AccessConditions}   [options.accessConditions]                  The access conditions.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link LeaseResult}` will contain
*                                                                         the lease information.
*                                                                         `response` will contain information related to this operation.
*/
BlobService.prototype.breakLease = function (container, blob, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('breakLease', function (v) {
    v.string(container, 'container');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
 
  this._leaseImpl(container, blob, null /*leaseId*/, BlobConstants.LeaseOperation.BREAK, options, callback);
};
 
// Blob methods
 
/**
* Returns all user-defined metadata, standard HTTP properties, and system properties for the blob.
* It does not return or modify the content of the blob.
* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive.
*
* @this {BlobService}
* @param {string}             container                                   The container name.
* @param {string}             blob                                        The blob name.
* @param {object}             [options]                                   The request options.
* @param {string}             [options.snapshotId]                        The snapshot identifier.
* @param {string}             [options.leaseId]                           The lease identifier.
* @param {AccessConditions}   [options.accessConditions]                  The access conditions.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link BlobResult}` will contain
*                                                                         information about the blob.
*                                                                         `response` will contain information related to this operation.
*/
BlobService.prototype.getBlobProperties = function (container, blob, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('getBlobProperties', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var resourceName = createResourceName(container, blob);
  var webResource = WebResource.head(resourceName);
 
  if (options.snapshotId) {
    webResource.withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId);
  }
 
  BlobResult.setHeadersFromBlob(webResource, options);
 
  options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
 
  var self = this;
  var processResponseCallback = function (responseObject, next) {
    responseObject.blobResult = null;
    if (!responseObject.error) {
      responseObject.blobResult = new BlobResult(container, blob);
      responseObject.blobResult.metadata = self.parseMetadataHeaders(responseObject.response.headers);
      responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.blobResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Returns all user-defined metadata for the specified blob or snapshot.
* It does not modify or return the content of the blob.
* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive.
*
* @this {BlobService}
* @param {string}             container                                   The container name.
* @param {string}             blob                                        The blob name.
* @param {object}             [options]                                   The request options.
* @param {string}             [options.snapshotId]                        The snapshot identifier.
* @param {string}             [options.leaseId]                           The lease identifier.
* @param {AccessConditions}   [options.accessConditions]                  The access conditions.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link BlobResult}` will contain
*                                                                         information about the blob.
*                                                                         `response` will contain information related to this operation.
*/
BlobService.prototype.getBlobMetadata = function (container, blob, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('getBlobMetadata', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var resourceName = createResourceName(container, blob);
  var webResource = WebResource.head(resourceName);
 
  webResource.withQueryOption(QueryStringConstants.COMP, 'metadata');
  webResource.withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId);
 
  BlobResult.setHeadersFromBlob(webResource, options);
 
  options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
 
  var self = this;
  var processResponseCallback = function (responseObject, next) {
    responseObject.blobResult = null;
    if (!responseObject.error) {
      responseObject.blobResult = new BlobResult(container, blob);
      responseObject.blobResult.metadata = self.parseMetadataHeaders(responseObject.response.headers);
      responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.blobResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Sets user-defined properties for the specified blob or snapshot.
* It does not modify or return the content of the blob.
*
* @this {BlobService}
* @param {string}             container                                   The container name.
* @param {string}             blob                                        The blob name.
* @param {object}             [properties]                                The blob properties to set.
* @param {string}             [properties.contentType]                    The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [properties.contentEncoding]                The content encodings that have been applied to the blob.
* @param {string}             [properties.contentLanguage]                The natural languages used by this resource.
* @param {string}             [properties.cacheControl]                   The blob's cache control.
* @param {string}             [properties.contentDisposition]             The blob's content disposition.
* @param {string}             [properties.contentMD5]                     The blob's MD5 hash.
* @param {object}             [options]                                   The request options.
* @param {string}             [options.leaseId]                           The lease identifier.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {AccessConditions}   [options.accessConditions]                  The access conditions.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link BlobResult}` will contain
*                                                                         information about the blob.
*                                                                         `response` will contain information related to this operation.
*/
BlobService.prototype.setBlobProperties = function (container, blob, properties, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('setBlobProperties', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, { contentSettings: properties }, userOptions);
  var resourceName = createResourceName(container, blob);
  var webResource = WebResource.put(resourceName)
    .withQueryOption(QueryStringConstants.COMP, 'properties');
 
  BlobResult.setPropertiesFromBlob(webResource, options);
 
  this._setBlobPropertiesHelper({
    webResource: webResource,
    options: options,
    container: container,
    blob: blob,
    callback: callback
  });
};
 
/**
* Sets user-defined metadata for the specified blob or snapshot as one or more name-value pairs 
* It does not modify or return the content of the blob.
*
* @this {BlobService}
* @param {string}             container                                   The container name.
* @param {string}             blob                                        The blob name.
* @param {object}             metadata                                    The metadata key/value pairs.
* @param {object}             [options]                                   The request options.
* @param {string}             [options.snapshotId]                        The snapshot identifier.
* @param {string}             [options.leaseId]                           The lease identifier.
* @param {AccessConditions}   [options.accessConditions]                  The access conditions.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link BlobResult}` will contain
*                                                                         information on the blob.
*                                                                         `response` will contain information related to this operation.
*/
BlobService.prototype.setBlobMetadata = function (container, blob, metadata, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('setBlobMetadata', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.object(metadata, 'metadata');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var resourceName = createResourceName(container, blob);
  var webResource = WebResource.put(resourceName)
    .withQueryOption(QueryStringConstants.COMP, 'metadata');
 
  webResource.withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId);
 
  options.metadata = metadata;
  BlobResult.setHeadersFromBlob(webResource, options);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.blobResult = null;
    if (!responseObject.error) {
      responseObject.blobResult = new BlobResult(container, blob);
      responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.blobResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Downloads a blob into a file.
* (Not recommended for use in the JavaScript Client Library)
*
* @this {BlobService}
* @param {string}             container                                   The container name.
* @param {string}             blob                                        The blob name.
* @param {string}             localFileName                               The local path to the file to be downloaded.
* @param {object}             [options]                                   The request options.
* @param {boolean}            [options.skipSizeCheck]                     Skip the size check to perform direct download.
*                                                                         Set the option to true for small blobs.
*                                                                         Parallel download and speed summary won't work with this option on.
* @param {SpeedSummary}       [options.speedSummary]                      The download tracker objects.
* @param {int}                [options.parallelOperationThreadCount]      Parallel operation thread count.
* @param {string}             [options.snapshotId]                        The snapshot identifier.
* @param {string}             [options.leaseId]                           The lease identifier.
* @param {string}             [options.rangeStart]                        Return only the bytes of the blob in the specified range.
* @param {string}             [options.rangeEnd]                          Return only the bytes of the blob in the specified range.
* @param {AccessConditions}   [options.accessConditions]                  The access conditions.
* @param {boolean}            [options.useTransactionalMD5]               When set to true, Calculate and send/validate content MD5 for transactions.
* @param {boolean}            [options.disableContentMD5Validation]       When set to true, MD5 validation will be disabled when downloading blobs.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information if an error occurs; 
*                                                                         otherwise `[result]{@link BlobResult}` will contain the blob information.
*                                                                         `response` will contain information related to this operation.
* @return {SpeedSummary}
* 
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
* blobService.getBlobToLocalFile('taskcontainer', 'task1', 'task1-download.txt', function(error, serverBlob) {
*   if(!error) {
*     // Blob available in serverBlob.blob variable
*   }
*/
BlobService.prototype.getBlobToLocalFile = function (container, blob, localFileName, optionsOrCallback, callback) {
  var options;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; });
 
  validate.validateArgs('getBlobToLocalFile', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.string(localFileName, 'localFileName');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
  
  return this._getBlobToLocalFile(container, blob, localFileName, options, callback);
};
 
/**
* Provides a stream to read from a blob.
*
* @this {BlobService}
* @param {string}             container                                   The container name.
* @param {string}             blob                                        The blob name.
* @param {object}             [options]                                   The request options.
* @param {string}             [options.snapshotId]                        The snapshot identifier.
* @param {string}             [options.leaseId]                           The lease identifier.
* @param {string}             [options.rangeStart]                        Return only the bytes of the blob in the specified range.
* @param {string}             [options.rangeEnd]                          Return only the bytes of the blob in the specified range.
* @param {AccessConditions}   [options.accessConditions]                  The access conditions.
* @param {boolean}            [options.useTransactionalMD5]               When set to true, Calculate and send/validate content MD5 for transactions.
* @param {boolean}            [options.disableContentMD5Validation]       When set to true, MD5 validation will be disabled when downloading blobs.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information if an error occurs; 
*                                                                         otherwise `[result]{@link BlobResult}` will contain the blob information.
*                                                                         `response` will contain information related to this operation.
* @return {Stream}
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
* var writable = fs.createWriteStream(destinationFileNameTarget);
*  blobService.createReadStream(containerName, blobName).pipe(writable);
*/
BlobService.prototype.createReadStream = function (container, blob, optionsOrCallback, callback) {
  var options;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; });
 
  validate.validateArgs('createReadStream', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
  });
 
  var readStream = new ChunkStream();
  this.getBlobToStream(container, blob, readStream, options, function (error, responseBlob, response) {
    if (error) {
      readStream.emit('error', error);
    }
 
    if (callback) {
      callback(error, responseBlob, response);
    }
  });
 
  return readStream;
};
 
/**
* Downloads a blob into a stream.
*
* @this {BlobService}
* @param {string}             container                                   The container name.
* @param {string}             blob                                        The blob name.
* @param {Stream}             writeStream                                 The write stream.
* @param {object}             [options]                                   The request options.
* @param {boolean}            [options.skipSizeCheck]                     Skip the size check to perform direct download.
*                                                                         Set the option to true for small blobs.
*                                                                         Parallel download and speed summary won't work with this option on.
* @param {SpeedSummary}       [options.speedSummary]                      The download tracker objects.
* @param {int}                [options.parallelOperationThreadCount]      Parallel operation thread count.
* @param {string}             [options.snapshotId]                        The snapshot identifier.
* @param {string}             [options.leaseId]                           The lease identifier.
* @param {string}             [options.rangeStart]                        Return only the bytes of the blob in the specified range.
* @param {string}             [options.rangeEnd]                          Return only the bytes of the blob in the specified range. 
* @param {boolean}            [options.useTransactionalMD5]               When set to true, Calculate and send/validate content MD5 for transactions.
* @param {boolean}            [options.disableContentMD5Validation]       When set to true, MD5 validation will be disabled when downloading blobs.
* @param {AccessConditions}   [options.accessConditions]                  The access conditions.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information if an error occurs; 
*                                                                         otherwise `[result]{@link BlobResult}` will contain the blob information.
*                                                                         `response` will contain information related to this operation.
* @return {SpeedSummary}
*
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
* blobService.getBlobToStream('taskcontainer', 'task1', fs.createWriteStream('task1-download.txt'), function(error, serverBlob) {
*   if(!error) {
*     // Blob available in serverBlob.blob variable
*   }
* }); 
*/
BlobService.prototype.getBlobToStream = function (container, blob, writeStream, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  userOptions.speedSummary = userOptions.speedSummary || new SpeedSummary(blob);
  
  validate.validateArgs('getBlobToStream', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.object(writeStream, 'writeStream');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  
  var propertiesRequestOptions = {
    timeoutIntervalInMs : options.timeoutIntervalInMs,
    clientRequestTimeoutInMs: options.clientRequestTimeoutInMs,
    snapshotId : options.snapshotId,
    accessConditions : options.accessConditions
  };
  
  if (options.skipSizeCheck) {
    this._getBlobToStream(container, blob, writeStream, options, callback);
  } else {
    var self = this;
    this.getBlobProperties(container, blob, propertiesRequestOptions, function (error, properties) {
      if (error) {
        callback(error);
      } else {
        var size;
        if (options.rangeStart) {
          var endOffset = properties.contentLength - 1;
          var end = options.rangeEnd ? Math.min(options.rangeEnd, endOffset) : endOffset;
          size = end - options.rangeStart + 1;
        } else {
          size = properties.contentLength;
        }
        options.speedSummary.totalSize = size;
        
        if (size > self.singleBlobPutThresholdInBytes) {
          azureutil.setObjectInnerPropertyValue(options, ['contentSettings', 'contentMD5'], azureutil.tryGetValueChain(properties, ['contentSettings', 'contentMD5'], null));
          self._getBlobToRangeStream(container, blob, properties.blobType, writeStream, options, callback);
        } else {
          self._getBlobToStream(container, blob, writeStream, options, callback);
        }
      }
    });
  }
  
  return options.speedSummary;
};
 
/**
* Downloads a blob into a text string.
*
* @this {BlobService}
* @param {string}             container                                   The container name.
* @param {string}             blob                                        The blob name.
* @param {object}             [options]                                   The request options.
* @param {string}             [options.snapshotId]                        The snapshot identifier.
* @param {string}             [options.leaseId]                           The lease identifier. 
* @param {string}             [options.rangeStart]                        Return only the bytes of the blob in the specified range.
* @param {string}             [options.rangeEnd]                          Return only the bytes of the blob in the specified range.
* @param {bool}               [options.useTransactionalMD5]               Calculate and send/validate content MD5 for transactions.
* @param {boolean}            [options.disableContentMD5Validation]       When set to true, MD5 validation will be disabled when downloading blobs.
* @param {AccessConditions}   [options.accessConditions]                  The access conditions.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {BlobService~blobToText}  callback                               `error` will contain information
*                                                                         if an error occurs; otherwise `text` will contain the blob contents,
*                                                                         and `[blockBlob]{@link BlobResult}` will contain
*                                                                         the blob information.
*                                                                         `response` will contain information related to this operation.
*/
BlobService.prototype.getBlobToText = function (container, blob, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('getBlobToText', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var resourceName = createResourceName(container, blob);
  var webResource = WebResource.get(resourceName)
    .withRawResponse();
  
  webResource.withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId);
 
  BlobResult.setHeadersFromBlob(webResource, options);
  this._setRangeContentMD5Header(webResource, options);
 
  options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
 
  var self = this;
  var processResponseCallback = function (responseObject, next) {
    responseObject.text = null;
    responseObject.blobResult = null;
 
    if (!responseObject.error) {
      responseObject.blobResult = new BlobResult(container, blob);
      responseObject.blobResult.metadata = self.parseMetadataHeaders(responseObject.response.headers);
      responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
      responseObject.text = responseObject.response.body;
 
      self._validateLengthAndMD5(options, responseObject);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.text, returnObject.blobResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Marks the specified blob or snapshot for deletion. The blob is later deleted during garbage collection.
* If a blob has snapshots, you must delete them when deleting the blob. Using the deleteSnapshots option, you can choose either to delete both the blob and its snapshots, 
* or to delete only the snapshots but not the blob itself. If the blob has snapshots, you must include the deleteSnapshots option or the blob service will return an error
* and nothing will be deleted. 
* If you are deleting a specific snapshot using the snapshotId option, the deleteSnapshots option must NOT be included.
*
* @this {BlobService}
* @param {string}             container                                   The container name.
* @param {string}             blob                                        The blob name.
* @param {object}             [options]                                   The request options.
* @param {string}             [options.deleteSnapshots]                   The snapshot delete option. See azure.BlobUtilities.SnapshotDeleteOptions.*. 
* @param {string}             [options.snapshotId]                        The snapshot identifier.
* @param {string}             [options.leaseId]                           The lease identifier.
* @param {AccessConditions}   [options.accessConditions]                  The access conditions.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResponse}    callback                                    `error` will contain information
*                                                                         if an error occurs; `response` will contain information related to this operation.
*/
BlobService.prototype.deleteBlob = function (container, blob, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('deleteBlob', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var resourceName = createResourceName(container, blob);
  var webResource = WebResource.del(resourceName)
    .withHeader(HeaderConstants.LEASE_ID, options.leaseId);
 
  if (!azureutil.objectIsNull(options.snapshotId) && !azureutil.objectIsNull(options.deleteSnapshots)) {
    throw new ArgumentError('options', SR.INVALID_DELETE_SNAPSHOT_OPTION);
  }
    
  webResource.withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId);
  webResource.withHeader(HeaderConstants.DELETE_SNAPSHOT, options.deleteSnapshots);
 
  BlobResult.setHeadersFromBlob(webResource, options);
 
  var processResponseCallback = function (responseObject, next) {
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Checks whether or not a blob exists on the service.
*
* @this {BlobService}
* @param {string}             container                               The container name.
* @param {string}             blob                                    The blob name.
* @param {object}             [options]                               The request options.
* @param {LocationMode}       [options.locationMode]                  Specifies the location mode used to decide which location the request should be sent to. 
*                                                                     Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]           The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]      The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]      The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                     The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                     execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]               A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]             Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                     The default value is false.
* @param {Function(error, result, response)}  callback                `error` will contain information
*                                                                     if an error occurs; otherwise `[result]{@link BlobResult}` will contain 
*                                                                     the blob information including the `exists` boolean member. 
*                                                                     `response` will contain information related to this operation.
*/
BlobService.prototype.doesBlobExist = function (container, blob, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('doesBlobExist', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
 
  this._doesBlobExist(container, blob, false, options, callback);
};
 
/**
* Marks the specified blob or snapshot for deletion if it exists. The blob is later deleted during garbage collection.
* If a blob has snapshots, you must delete them when deleting the blob. Using the deleteSnapshots option, you can choose either to delete both the blob and its snapshots, 
* or to delete only the snapshots but not the blob itself. If the blob has snapshots, you must include the deleteSnapshots option or the blob service will return an error
* and nothing will be deleted. 
* If you are deleting a specific snapshot using the snapshotId option, the deleteSnapshots option must NOT be included.
*
* @this {BlobService}
* @param {string}             container                           The container name.
* @param {string}             blob                                The blob name.
* @param {object}             [options]                           The request options.
* @param {string}             [options.deleteSnapshots]           The snapshot delete option. See azure.BlobUtilities.SnapshotDeleteOptions.*. 
* @param {string}             [options.snapshotId]                The snapshot identifier.
* @param {string}             [options.leaseId]                   The lease identifier.
* @param {AccessConditions}   [options.accessConditions]          The access conditions.
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise `result` will
*                                                                 be true if the blob was deleted, or false if the blob
*                                                                 does not exist.
*                                                                 `response` will contain information related to this operation.
*/
BlobService.prototype.deleteBlobIfExists = function (container, blob, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('deleteBlobIfExists', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var self = this;
  self._doesBlobExist(container, blob, true, options, function (error, existsResult, response) {
    if (error) {
      callback(error, existsResult.exists, response);
    } else if (!existsResult.exists) {
      response.isSuccessful = true;
      callback(error, false, response);
    } else {
      self.deleteBlob(container, blob, options, function (deleteError, deleteResponse) {
        var deleted;
        if (!deleteError) {
          deleted = true;
        } else if (deleteError && deleteError.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound && deleteError.code === Constants.BlobErrorCodeStrings.BLOB_NOT_FOUND) {
          // If it was deleted already, there was no actual error.
          deleted = false;
          deleteError = null;
          deleteResponse.isSuccessful = true;
        }
 
        callback(deleteError, deleted, deleteResponse);
      });
    }
  });
};
 
/**
* Creates a read-only snapshot of a blob.
*
* @this {BlobService}
* @param {string}             container                             The container name.
* @param {string}             blob                                  The blob name.
* @param {object}             [options]                             The request options.
* @param {string}             [options.snapshotId]                  The snapshot identifier.
* @param {object}             [options.metadata]                    The metadata key/value pairs.
* @param {string}             [options.leaseId]                     The lease identifier.
* @param {AccessConditions}   [options.accessConditions]            The access conditions.
* @param {LocationMode}       [options.locationMode]                Specifies the location mode used to decide which location the request should be sent to. 
*                                                                   Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]         The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]    The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]    The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                   The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                   execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]             A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]           Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                   The default value is false.
* @param {errorOrResult}      callback                              `error` will contain information
*                                                                   if an error occurs; otherwise `result` will contain
*                                                                   the ID of the snapshot.
*                                                                   `response` will contain information related to this operation.
*/
BlobService.prototype.createBlobSnapshot = function (container, blob, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('createBlobSnapshot', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var resourceName = createResourceName(container, blob);
  var webResource = WebResource.put(resourceName)
    .withQueryOption(QueryStringConstants.COMP, 'snapshot');
 
  BlobResult.setHeadersFromBlob(webResource, options);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.snapshotId = null;
    if (!responseObject.error) {
      responseObject.snapshotId = responseObject.response.headers[HeaderConstants.SNAPSHOT];
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.snapshotId, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Starts to copy a blob to a destination within the storage account. The Copy Blob operation copies the entire committed blob.
*
* @this {BlobService}
* @param {string}             sourceUri                                 The source blob URI.
* @param {string}             targetContainer                           The target container name.
* @param {string}             targetBlob                                The target blob name.
* @param {object}             [options]                                 The request options.
* @param {boolean}            [options.isIncrementalCopy]               If it's incremental copy or not. Refer to https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/incremental-copy-blob
* @param {string}             [options.snapshotId]                      The source blob snapshot identifier.
* @param {object}             [options.metadata]                        The target blob metadata key/value pairs.
* @param {string}             [options.leaseId]                         The target blob lease identifier.
* @param {string}             [options.sourceLeaseId]                   The source blob lease identifier.
* @param {AccessConditions}   [options.accessConditions]                The access conditions.
* @param {AccessConditions}   [options.sourceAccessConditions]          The source access conditions.
* @param {LocationMode}       [options.locationMode]                    Specifies the location mode used to decide which location the request should be sent to. 
*                                                                       Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]             The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]        The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]        The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                       The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                       execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                 A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]               Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                       The default value is false.
* @param {errorOrResult}      callback                                  `error` will contain information
*                                                                       if an error occurs; otherwise `[result]{@link BlobResult}` will contain
*                                                                       the blob information.
*                                                                       `response` will contain information related to this operation.
*/
BlobService.prototype.startCopyBlob = function (sourceUri, targetContainer, targetBlob, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('startCopyBlob', function (v) {
    v.string(sourceUri, 'sourceUri');
    v.string(targetContainer, 'targetContainer');
    v.string(targetBlob, 'targetBlob');
    v.containerNameIsValid(targetContainer);
    v.callback(callback);
  });
 
  var targetResourceName = createResourceName(targetContainer, targetBlob);
 
  var options = extend(true, {}, userOptions);
 
  if (options.snapshotId) {
    var uri = url.parse(sourceUri, true);
    if(uri.query['snapshot']) {
      throw new ArgumentError('options.snapshotId', 'Duplicate snapshot supplied in both the source uri and option.');
    }
    
    uri.search = undefined;
    uri.query['snapshot'] = options.snapshotId;
    
    sourceUri = url.format(uri);
  }
 
  var webResource = WebResource.put(targetResourceName)
    .withHeader(HeaderConstants.COPY_SOURCE, sourceUri);
 
  if (options.isIncrementalCopy) {
    webResource.withQueryOption(QueryStringConstants.COMP, 'incrementalcopy');
  }
 
  webResource.withHeader(HeaderConstants.LEASE_ID, options.leaseId);
  webResource.withHeader(HeaderConstants.SOURCE_LEASE_ID, options.sourceLeaseId);
  webResource.addOptionalMetadataHeaders(options.metadata);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.blobResult = null;
    if (!responseObject.error) {
      responseObject.blobResult = new BlobResult(targetContainer, targetBlob);
      responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
 
      if (options.metadata) {
        responseObject.blobResult.metadata = options.metadata;
      }
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.blobResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Abort a blob copy operation.
*
* @this {BlobService}
* @param {string}             container                                 The destination container name.
* @param {string}             blob                                      The destination blob name.
* @param {string}             copyId                                    The copy operation identifier.
* @param {object}             [options]                                 The request options.
* @param {string}             [options.leaseId]                         The target blob lease identifier.
* @param {LocationMode}       [options.locationMode]                    Specifies the location mode used to decide which location the request should be sent to. 
*                                                                       Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]             The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]        The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]        The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                       The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                       execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                 A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]               Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                       The default value is false.
* @param {errorOrResponse}    callback                                  `error` will contain information  if an error occurs; 
*                                                                       `response` will contain information related to this operation.
*/
BlobService.prototype.abortCopyBlob = function (container, blob, copyId, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('abortCopyBlob', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var resourceName = createResourceName(container, blob);
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.put(resourceName)
    .withQueryOption(QueryStringConstants.COPY_ID, copyId)
    .withQueryOption(QueryStringConstants.COMP, 'copy')
    .withHeader(HeaderConstants.COPY_ACTION, 'abort');
 
  webResource.withHeader(HeaderConstants.LEASE_ID, options.leaseId);
 
  var processResponseCallback = function (responseObject, next) {
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Retrieves a shared access signature token.
*
* @this {BlobService}
* @param {string}                   container                                           The container name.
* @param {string}                   [blob]                                              The blob name.
* @param {object}                   sharedAccessPolicy                                  The shared access policy.
* @param {string}                   [sharedAccessPolicy.Id]                             The signed identifier.
* @param {object}                   [sharedAccessPolicy.AccessPolicy.Permissions]       The permission type.
* @param {date|string}              [sharedAccessPolicy.AccessPolicy.Start]             The time at which the Shared Access Signature becomes valid (The UTC value will be used).
* @param {date|string}              [sharedAccessPolicy.AccessPolicy.Expiry]            The time at which the Shared Access Signature becomes expired (The UTC value will be used).
* @param {string}                   [sharedAccessPolicy.AccessPolicy.IPAddressOrRange]  An IP address or a range of IP addresses from which to accept requests. When specifying a range, note that the range is inclusive.
* @param {string}                   [sharedAccessPolicy.AccessPolicy.Protocols]         The protocols permitted for a request made with the account SAS. 
*                                                                                       Possible values are both HTTPS and HTTP (https,http) or HTTPS only (https). The default value is https,http.
* @param {object}                   [headers]                                           The optional header values to set for a blob returned wth this SAS.
* @param {string}                   [headers.cacheControl]                              The optional value of the Cache-Control response header to be returned when this SAS is used.
* @param {string}                   [headers.contentType]                               The optional value of the Content-Type response header to be returned when this SAS is used.
* @param {string}                   [headers.contentEncoding]                           The optional value of the Content-Encoding response header to be returned when this SAS is used.
* @param {string}                   [headers.contentLanguage]                           The optional value of the Content-Language response header to be returned when this SAS is used.
* @param {string}                   [headers.contentDisposition]                        The optional value of the Content-Disposition response header to be returned when this SAS is used.
* @return {string}                                                                      The shared access signature query string. Note this string does not contain the leading "?".
*/
BlobService.prototype.generateSharedAccessSignature = function (container, blob, sharedAccessPolicy, headers) {
  // check if the BlobService is able to generate a shared access signature
  if (!this.storageCredentials){
    throw new ArgumentNullError('storageCredentials');
  }
 
  if(!this.storageCredentials.generateSignedQueryString) {
    throw new ArgumentError('storageCredentials', SR.CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY);
  }
 
  // Validate container name. Blob name is optional.
  validate.validateArgs('generateSharedAccessSignature', function (v) {
    v.string(container, 'container');
    v.containerNameIsValid(container);
    v.object(sharedAccessPolicy, 'sharedAccessPolicy');
  });
 
  var resourceType = BlobConstants.ResourceTypes.CONTAINER;
  if (blob) {
    validate.validateArgs('generateSharedAccessSignature', function (v) {
      v.string(blob, 'blob');
    });
    resourceType = BlobConstants.ResourceTypes.BLOB;
  }
 
  if (sharedAccessPolicy.AccessPolicy) {
    if (!azureutil.objectIsNull(sharedAccessPolicy.AccessPolicy.Start)) {
      if (!_.isDate(sharedAccessPolicy.AccessPolicy.Start)) {
        sharedAccessPolicy.AccessPolicy.Start = new Date(sharedAccessPolicy.AccessPolicy.Start);
      }
 
      sharedAccessPolicy.AccessPolicy.Start = azureutil.truncatedISO8061Date(sharedAccessPolicy.AccessPolicy.Start);
    }
 
    if (!azureutil.objectIsNull(sharedAccessPolicy.AccessPolicy.Expiry)) {
      if (!_.isDate(sharedAccessPolicy.AccessPolicy.Expiry)) {
        sharedAccessPolicy.AccessPolicy.Expiry = new Date(sharedAccessPolicy.AccessPolicy.Expiry);
      }
 
      sharedAccessPolicy.AccessPolicy.Expiry = azureutil.truncatedISO8061Date(sharedAccessPolicy.AccessPolicy.Expiry);
    }
  }
 
  var resourceName = createResourceName(container, blob, true);
  return this.storageCredentials.generateSignedQueryString(Constants.ServiceType.Blob, resourceName, sharedAccessPolicy, null, { headers: headers, resourceType: resourceType });
};
 
/**
* Retrieves a blob or container URL.
*
* @param {string}                   container                The container name.
* @param {string}                   [blob]                   The blob name.
* @param {string}                   [sasToken]               The Shared Access Signature token.
* @param {boolean}                  [primary]                A boolean representing whether to use the primary or the secondary endpoint.
* @param {boolean}                  [snapshotId]             The snapshot identifier.
* @return {string}                                           The formatted URL string.
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
* var sharedAccessPolicy = {
*   AccessPolicy: {
*     Permissions: azure.BlobUtilities.SharedAccessPermissions.READ,
*     Start: startDate,
*     Expiry: expiryDate
*   },
* };
* 
* var sasToken = blobService.generateSharedAccessSignature(containerName, blobName, sharedAccessPolicy);
* var sasUrl = blobService.getUrl(containerName, blobName, sasToken);
*/
BlobService.prototype.getUrl = function (container, blob, sasToken, primary, snapshotId) {
  validate.validateArgs('getUrl', function (v) {
    v.string(container, 'container');
    v.containerNameIsValid(container);
  });
 
  var host;
  if (!azureutil.objectIsNull(primary) && primary === false) {
    host = this.host.secondaryHost;
  } else {
    host = this.host.primaryHost;
  }
 
  host = azureutil.trimPortFromUri(host);
  if(host && host.lastIndexOf('/') !== (host.length - 1)){
    host = host + '/';
  }
 
  var query = qs.parse(sasToken);
  if(snapshotId) {
    query[QueryStringConstants.SNAPSHOT] = snapshotId;
  }
 
  var fullPath = url.format({ pathname: this._getPath(createResourceName(container, blob)), query: query });
  return url.resolve(host, fullPath);
};
 
// Page blob methods
 
/**
* Creates a page blob of the specified length. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
*
* @this {BlobService}
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param {int}                length                                        The length of the page blob in bytes.
* @param {object}             [options]                                     The request options.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {string}             [options.leaseId]                             The target blob lease identifier.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The MD5 hash of the blob content.
* @param {string}             [options.sequenceNumber]                      The blob's sequence number.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResponse}    callback                                      `error` will contain information
*                                                                           if an error occurs; otherwise 
*                                                                           `response` will contain information related to this operation.
*/
BlobService.prototype.createPageBlob = function (container, blob, length, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('createPageBlob', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.value(length, 'length');
    v.callback(callback);
  });
 
  if (length && length % BlobConstants.PAGE_SIZE !== 0) {
    throw new RangeError(SR.INVALID_PAGE_BLOB_LENGTH);
  }
 
  var options = extend(true, {}, userOptions);
 
  var resourceName = createResourceName(container, blob);
  
  var webResource = WebResource.put(resourceName)
    .withHeader(HeaderConstants.BLOB_TYPE, BlobConstants.BlobTypes.PAGE)
    .withHeader(HeaderConstants.BLOB_CONTENT_LENGTH, length)
    .withHeader(HeaderConstants.CONTENT_LENGTH, 0)
    .withHeader(HeaderConstants.LEASE_ID, options.leaseId);
 
  BlobResult.setHeadersFromBlob(webResource, options);
 
  var processResponseCallback = function (responseObject, next) {
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Uploads a page blob from file. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
* (Not recommended for use in the JavaScript Client Library)
*
* @this {BlobService}
* @param {string}             container                                           The container name.
* @param {string}             blob                                                The blob name.
* @param (string)             localFileName                                       The local path to the file to be uploaded.
* @param {object}             [options]                                           The request options.
* @param {SpeedSummary}       [options.speedSummary]                              The upload tracker objects.
* @param {int}                [options.parallelOperationThreadCount]              Parallel operation thread count.
* @param {string}             [options.leaseId]                                   The lease identifier.
* @param {string}             [options.transactionalContentMD5]                   An MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport.
* @param {object}             [options.metadata]                                  The metadata key/value pairs.
* @param {bool}               [options.storeBlobContentMD5]                       Specifies whether the blob's ContentMD5 header should be set on uploads. 
*                                                                                 The default value is false for page blobs.
* @param {bool}               [options.useTransactionalMD5]                       Calculate and send/validate content MD5 for transactions.
* @param {object}             [options.contentSettings]                           The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]               The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]           The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]           The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]              The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]        The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]                The blob's MD5 hash.
* @param {AccessConditions}   [options.accessConditions]                          The access conditions.
* @param {LocationMode}       [options.locationMode]                              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]                  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]                  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                                 The default value is false.
* @param {errorOrResult}      callback                                            `error` will contain information
*                                                                                 if an error occurs; otherwise `[result]{@link BlobResult}` will contain
*                                                                                 the blob information.
*                                                                                 `response` will contain information related to this operation.
* @return {SpeedSummary}
*/
BlobService.prototype.createPageBlobFromLocalFile = function (container, blob, localFileName, optionsOrCallback, callback) {
  return this._createBlobFromLocalFile(container, blob, BlobConstants.BlobTypes.PAGE, localFileName, optionsOrCallback, callback);
};
 
/**
* Uploads a page blob from a stream. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
*
* @this {BlobService}
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param (Stream)             stream                                        Stream to the data to store.
* @param {int}                streamLength                                  The length of the stream to upload.
* @param {object}             [options]                                     The request options.
* @param {SpeedSummary}       [options.speedSummary]                        The download tracker objects;
* @param {int}                [options.parallelOperationThreadCount]        Parallel operation thread count.
* @param {string}             [options.leaseId]                             The lease identifier.
* @param {string}             [options.transactionalContentMD5]             An MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {bool}               [options.storeBlobContentMD5]                 Specifies whether the blob's ContentMD5 header should be set on uploads. 
*                                                                           The default value is false for page blobs.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The blob's MD5 hash.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      `error` will contain information
*                                                                           if an error occurs; otherwise `[result]{@link BlobResult}` will contain
*                                                                           the blob information.
*                                                                           `response` will contain information related to this operation.
* @return {SpeedSummary}
*/
BlobService.prototype.createPageBlobFromStream = function (container, blob, stream, streamLength, optionsOrCallback, callback) {
  return this._createBlobFromStream(container, blob, BlobConstants.BlobTypes.PAGE, stream, streamLength, optionsOrCallback, callback);
};
 
/**
* Provides a stream to write to a page blob. Assumes that the blob exists. 
* If it does not, please create the blob using createPageBlob before calling this method or use createWriteStreamNewPageBlob.
*
* @this {BlobService}
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param {object}             [options]                                     The request options.
* @param {string}             [options.leaseId]                             The lease identifier.
* @param {string}             [options.transactionalContentMD5]             The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {int}                [options.parallelOperationThreadCount]        Parallel operation thread count.
* @param {bool}               [options.storeBlobContentMD5]                 Specifies whether the blob's ContentMD5 header should be set on uploads. 
*                                                                           The default value is false for page blobs and true for block blobs.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The blob's MD5 hash.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      `error` will contain information
*                                                                           if an error occurs; otherwise `[result]{@link BlobResult}` will contain
*                                                                           the blob information.
*                                                                           `response` will contain information related to this operation.
* @return {Stream}
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
* blobService.createPageBlob(containerName, blobName, 1024, function (err) {
*   // Pipe file to a blob
*   var stream = fs.createReadStream(fileNameTarget).pipe(blobService.createWriteStreamToExistingPageBlob(containerName, blobName));
* });
*/
BlobService.prototype.createWriteStreamToExistingPageBlob = function (container, blob, optionsOrCallback, callback) {
  return this._createWriteStreamToBlob(container, blob, BlobConstants.BlobTypes.PAGE, 0, false, optionsOrCallback, callback);
};
 
/**
* Provides a stream to write to a page blob. Creates the blob before writing data. If the blob already exists on the service, it will be overwritten.
*
* @this {BlobService}
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param {string}             length                                        The blob length.
* @param {object}             [options]                                     The request options.
* @param {string}             [options.leaseId]                             The lease identifier.
* @param {string}             [options.transactionalContentMD5]             The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {int}                [options.parallelOperationThreadCount]        Parallel operation thread count.
* @param {bool}               [options.storeBlobContentMD5]                 Specifies whether the blob's ContentMD5 header should be set on uploads. 
*                                                                           The default value is false for page blobs and true for block blobs.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The blob's MD5 hash.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      `error` will contain information
*                                                                           if an error occurs; otherwise `[result]{@link BlobResult}` will contain
*                                                                           the blob information.
*                                                                           `response` will contain information related to this operation.
* @return {Stream}
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
* blobService.createPageBlob(containerName, blobName, 1024, function (err) {
*   // Pipe file to a blob
*   var stream = fs.createReadStream(fileNameTarget).pipe(blobService.createWriteStreamToNewPageBlob(containerName, blobName));
* });
*/
BlobService.prototype.createWriteStreamToNewPageBlob = function (container, blob, length, optionsOrCallback, callback) {
  return this._createWriteStreamToBlob(container, blob, BlobConstants.BlobTypes.PAGE, length, true, optionsOrCallback, callback);
};
 
/**
* Updates a page blob from a stream.
*
* @this {BlobService}
* @param {string}             container                                   The container name.
* @param {string}             blob                                        The blob name.
* @param {Stream}             readStream                                  The read stream.
* @param {int}                rangeStart                                  The range start.
* @param {int}                rangeEnd                                    The range end.
* @param {object}             [options]                                   The request options.
* @param {string}             [options.leaseId]                           The target blob lease identifier.
* @param {bool}               [options.useTransactionalMD5]               Calculate and send/validate content MD5 for transactions.
* @param {string}             [options.transactionalContentMD5]           An optional hash value used to ensure transactional integrity for the page. 
* @param {AccessConditions}   [options.accessConditions]                  The access conditions.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link BlobResult}` will contain
*                                                                         the page information.
*                                                                         `response` will contain information related to this operation.
*/
BlobService.prototype.createPagesFromStream = function (container, blob, readStream, rangeStart, rangeEnd, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('createPagesFromStream', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
 
  if ((rangeEnd - rangeStart) + 1 > BlobConstants.MAX_UPDATE_PAGE_SIZE) {
    throw new RangeError(SR.INVALID_PAGE_RANGE_FOR_UPDATE);
  }
 
  var self = this;
  if (azureutil.objectIsNull(options.transactionalContentMD5) && options.useTransactionalMD5) {
    azureutil.calculateMD5(readStream, BlobConstants.MAX_UPDATE_PAGE_SIZE, options, function (internalBuff, contentMD5) {
      options.transactionalContentMD5 = contentMD5;
      self._createPages(container, blob, internalBuff, null /* stream */, rangeStart, rangeEnd, options, callback);
    });
  } else {
    self._createPages(container, blob, null /* text */, readStream, rangeStart, rangeEnd, options, callback);
  }
};
 
/**
* Lists page ranges. Lists all of the page ranges by default, or only the page ranges over a specific range of bytes if rangeStart and rangeEnd are specified.
*
* @this {BlobService}
* @param {string}             container                                   The container name.
* @param {string}             blob                                        The blob name.
* @param {object}             [options]                                   The request options.
* @param {AccessConditions}   [options.accessConditions]                  The access conditions.
* @param {int}                [options.rangeStart]                        The range start.
* @param {int}                [options.rangeEnd]                          The range end.
* @param {string}             [options.snapshotId]                        The snapshot identifier.
* @param {string}             [options.leaseId]                           The target blob lease identifier.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `result` will contain
*                                                                         the page ranges information, see `[Range]{@link Range}` for detailed information.
*                                                                         `response` will contain information related to this operation.
*/
BlobService.prototype.listPageRanges = function (container, blob, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('listPageRanges', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
 
  var resourceName = createResourceName(container, blob);
  var webResource = WebResource.get(resourceName)
    .withQueryOption(QueryStringConstants.COMP, 'pagelist')
    .withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId);
 
  if (options.rangeStart && options.rangeStart % BlobConstants.PAGE_SIZE !== 0) {
    throw new RangeError(SR.INVALID_PAGE_START_OFFSET);
  }
 
  if (options.rangeEnd && (options.rangeEnd + 1) % BlobConstants.PAGE_SIZE !== 0) {
    throw new RangeError(SR.INVALID_PAGE_END_OFFSET);
  }
 
  BlobResult.setHeadersFromBlob(webResource, options);
 
  options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY;
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.pageRanges = null;
    if (!responseObject.error) {
      responseObject.pageRanges = [];
 
      var pageRanges = [];
      if (responseObject.response.body.PageList.PageRange) {
        pageRanges = responseObject.response.body.PageList.PageRange;
 
        if (!_.isArray(pageRanges)) {
          pageRanges = [ pageRanges ];
        }
      }
 
      pageRanges.forEach(function (pageRange) {
        var range = {
          start: parseInt(pageRange.Start, 10),
          end: parseInt(pageRange.End, 10)
        };
 
        responseObject.pageRanges.push(range);
      });
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.pageRanges, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Gets page ranges that have been updated or cleared since the snapshot specified by `previousSnapshotTime` was taken. Gets all of the page ranges by default, or only the page ranges over a specific range of bytes if rangeStart and rangeEnd are specified.
*
* @this {BlobService}
* @param {string}             container                                   The container name.
* @param {string}             blob                                        The blob name.
* @param {string}             previousSnapshotTime                        The previous snapshot time for comparison. Must be prior to `options.snapshotId` if it's provided.
* @param {object}             [options]                                   The request options.
* @param {AccessConditions}   [options.accessConditions]                  The access conditions.
* @param {int}                [options.rangeStart]                        The range start.
* @param {int}                [options.rangeEnd]                          The range end.
* @param {string}             [options.snapshotId]                        The snapshot identifier. 
* @param {string}             [options.leaseId]                           The target blob lease identifier.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `result` will contain
*                                                                         the page ranges diff information, see `[RangeDiff]{@link RangeDiff}` for detailed information.
*                                                                         `response` will contain information related to this operation.
*/
BlobService.prototype.getPageRangesDiff = function (container, blob, previousSnapshotTime, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('getPageRangesDiff', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
 
  var resourceName = createResourceName(container, blob);
  var webResource = WebResource.get(resourceName)
    .withQueryOption(QueryStringConstants.COMP, 'pagelist')
    .withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId)
    .withQueryOption(QueryStringConstants.PREV_SNAPSHOT, previousSnapshotTime);
 
  if (options.rangeStart && options.rangeStart % BlobConstants.PAGE_SIZE !== 0) {
    throw new RangeError(SR.INVALID_PAGE_START_OFFSET);
  }
 
  if (options.rangeEnd && (options.rangeEnd + 1) % BlobConstants.PAGE_SIZE !== 0) {
    throw new RangeError(SR.INVALID_PAGE_END_OFFSET);
  }
 
  if (options.rangeEnd && (options.rangeEnd + 1) % BlobConstants.PAGE_SIZE !== 0) {
    throw new RangeError(SR.INVALID_PAGE_END_OFFSET);
  }
 
  BlobResult.setHeadersFromBlob(webResource, options);
 
  options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY;
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.pageRangesDiff = null;
    if (!responseObject.error) {
      responseObject.pageRangesDiff = [];
 
      if (responseObject.response.body.PageList.PageRange) {
        var updatedPageRanges = responseObject.response.body.PageList.PageRange;
 
        if (!_.isArray(updatedPageRanges)) {
          updatedPageRanges = [ updatedPageRanges ];
        }
 
        updatedPageRanges.forEach(function (pageRange) {
          var range = {
            start: parseInt(pageRange.Start, 10),
            end: parseInt(pageRange.End, 10),
            isCleared: false
          };
 
          responseObject.pageRangesDiff.push(range);
        });
      }
 
      if (responseObject.response.body.PageList.ClearRange) {
        var clearedPageRanges = responseObject.response.body.PageList.ClearRange;
 
        if (!_.isArray(clearedPageRanges)) {
          clearedPageRanges = [ clearedPageRanges ];
        }
 
        clearedPageRanges.forEach(function (pageRange) {
          var range = {
            start: parseInt(pageRange.Start, 10),
            end: parseInt(pageRange.End, 10),
            isCleared: true
          };
 
          responseObject.pageRangesDiff.push(range);
        });
      }
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.pageRangesDiff, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Clears a range of pages.
*
* @this {BlobService}
* @param {string}             container                                   The container name.
* @param {string}             blob                                        The blob name.
* @param {int}                rangeStart                                  The range start.
* @param {int}                rangeEnd                                    The range end.
* @param {object}             [options]                                   The request options.
* @param {string}             [options.leaseId]                           The target blob lease identifier.
* @param {AccessConditions}   [options.accessConditions]                  The access conditions.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResponse}    callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise 
*                                                                         `response` will contain information related to this operation.
*/
BlobService.prototype.clearPageRange = function (container, blob, rangeStart, rangeEnd, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('clearPageRange', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var request = this._updatePageBlobPagesImpl(container, blob, rangeStart, rangeEnd, BlobConstants.PageWriteOptions.CLEAR, options);
 
  var self = this;
  var processResponseCallback = function (responseObject, next) {
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  self.performRequest(request, null, options, processResponseCallback);
};
 
/**
* Resizes a page blob.
*
* @this {BlobService}
* @param {string}               container                                   The container name.
* @param {string}               blob                                        The blob name.
* @param {String}               size                                        The size of the page blob, in bytes.
* @param {object}               [options]                                   The request options.
* @param {string}               [options.leaseId]                           The blob lease identifier.
* @param {AccessConditions}     [options.accessConditions]                  The access conditions.
* @param {LocationMode}         [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                  [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                  [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                  [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}               [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}                 [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      `error` will contain information
*                                                                           if an error occurs; otherwise `[result]{@link BlobResult}` will contain
*                                                                           the page information.
*                                                                           `response` will contain information related to this operation.
*/
BlobService.prototype.resizePageBlob = function (container, blob, size, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('resizePageBlob', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var resourceName = createResourceName(container, blob);
  var webResource = WebResource.put(resourceName)
    .withQueryOption(QueryStringConstants.COMP, 'properties');
 
  if (size && size % BlobConstants.PAGE_SIZE !== 0) {
    throw new RangeError(SR.INVALID_PAGE_BLOB_LENGTH);
  }
 
  webResource.withHeader(HeaderConstants.BLOB_CONTENT_LENGTH, size);
 
  this._setBlobPropertiesHelper({
    webResource: webResource,
    options: options,
    container: container,
    blob: blob,
    callback: callback
  });
  
};
 
/**
* Sets the page blob's sequence number.
*
* @this {BlobService}
* @param {string}               container                                   The container name.
* @param {string}               blob                                        The blob name.
* @param {SequenceNumberAction} sequenceNumberAction                        A value indicating the operation to perform on the sequence number. 
*                                                                           The allowed values are defined in azure.BlobUtilities.SequenceNumberAction.
* @param {string}               sequenceNumber                              The sequence number.  The value of the sequence number must be between 0 and 2^63 - 1.
*                                                                           Set this parameter to null if this operation is an increment action.
* @param {object}               [options]                                   The request options.
* @param {AccessConditions}     [options.accessConditions]                  The access conditions.
* @param {LocationMode}         [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                  [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                  [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                  [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}               [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}                 [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      `error` will contain information
*                                                                           if an error occurs; otherwise `[result]{@link BlobResult}` will contain
*                                                                           the page information.
*                                                                           `response` will contain information related to this operation.
*/
BlobService.prototype.setPageBlobSequenceNumber = function (container, blob, sequenceNumberAction, sequenceNumber, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('setPageBlobSequenceNumber', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  if (sequenceNumberAction === BlobUtilities.SequenceNumberAction.INCREMENT) {
    if (!azureutil.objectIsNull(sequenceNumber)) {
      throw new ArgumentError('sequenceNumber', SR.BLOB_INVALID_SEQUENCE_NUMBER);
    }
  } else {
    if (azureutil.objectIsNull(sequenceNumber)) {
      throw new ArgumentNullError('sequenceNumber', util.format(SR.ARGUMENT_NULL_OR_EMPTY, 'sequenceNumber'));
    }
  }
 
  var options = extend(true, {}, userOptions);
  var resourceName = createResourceName(container, blob);
  var webResource = WebResource.put(resourceName)
    .withQueryOption(QueryStringConstants.COMP, 'properties')
    .withHeader(HeaderConstants.SEQUENCE_NUMBER_ACTION, sequenceNumberAction);
 
  if (sequenceNumberAction !== BlobUtilities.SequenceNumberAction.INCREMENT) {
    webResource.withHeader(HeaderConstants.SEQUENCE_NUMBER, sequenceNumber);
  }
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.blobResult = null;
    if (!responseObject.error) {
      responseObject.blobResult = new BlobResult(container, blob);
      responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.blobResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
// Block blob methods
 
/**
* Creates a new block blob. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
* (Not recommended for use in the JavaScript Client Library)
*
* @this {BlobService}
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param {string}             localFileName                                 The local path to the file to be uploaded.
* @param {object}             [options]                                     The request options.
* @param {int}                [options.blockSize]                           The size of each block. Maximum is 100MB.
* @param {string}             [options.blockIdPrefix]                       The prefix to be used to generate the block id.
* @param {string}             [options.leaseId]                             The lease identifier.
* @param {string}             [options.transactionalContentMD5]             The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {int}                [options.parallelOperationThreadCount]        Parallel operation thread count.
* @param {bool}               [options.storeBlobContentMD5]                 Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The blob's MD5 hash.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      `error` will contain information
*                                                                           if an error occurs; otherwise `[result]{@link BlobResult}` will contain
*                                                                           the blob information.
*                                                                           `response` will contain information related to this operation.
* @return {SpeedSummary}
*/
BlobService.prototype.createBlockBlobFromLocalFile = function (container, blob, localFileName, optionsOrCallback, callback) {
  return this._createBlobFromLocalFile(container, blob, BlobConstants.BlobTypes.BLOCK, localFileName, optionsOrCallback, callback);
};
 
/**
* Uploads a block blob from a stream. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
*
* @this {BlobService}
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param (Stream)             stream                                        Stream to the data to store.
* @param {int}                streamLength                                  The length of the stream to upload.
* @param {object}             [options]                                     The request options.
* @param {SpeedSummary}       [options.speedSummary]                        The download tracker objects.
* @param {int}                [options.blockSize]                           The size of each block. Maximum is 100MB.
* @param {string}             [options.blockIdPrefix]                       The prefix to be used to generate the block id.
* @param {string}             [options.leaseId]                             The lease identifier.
* @param {string}             [options.transactionalContentMD5]             The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {int}                [options.parallelOperationThreadCount]        Parallel operation thread count.
* @param {bool}               [options.storeBlobContentMD5]                 Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The blob's MD5 hash.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      `error` will contain information
*                                                                           if an error occurs; otherwise `[result]{@link BlobResult}` will contain
*                                                                           the blob information.
*                                                                           `response` will contain information related to this operation.
* @return {SpeedSummary}
*/
BlobService.prototype.createBlockBlobFromStream = function (container, blob, stream, streamLength, optionsOrCallback, callback) {
  return this._createBlobFromStream(container, blob, BlobConstants.BlobTypes.BLOCK, stream, streamLength, optionsOrCallback, callback);
};
 
/**
* Uploads a block blob from a text string. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
*
* @this {BlobService}
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param {string|object}      text                                          The blob text, as a string or in a Buffer.
* @param {object}             [options]                                     The request options.
* @param {string}             [options.leaseId]                             The lease identifier.
* @param {string}             [options.transactionalContentMD5]             The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {bool}               [options.storeBlobContentMD5]                 Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The blob's MD5 hash.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      `error` will contain information
*                                                                           if an error occurs; otherwise `[result]{@link BlobResult}` will contain
*                                                                           the blob information.
*                                                                           `response` will contain information related to this operation.
*/
BlobService.prototype.createBlockBlobFromText = function (container, blob, text, optionsOrCallback, callback) {
  return this._createBlobFromText(container, blob, BlobConstants.BlobTypes.BLOCK, text, optionsOrCallback, callback);
};
 
/**
* Provides a stream to write to a block blob. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
*
* @this {BlobService}
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param {object}             [options]                                     The request options.
* @param {int}                [options.blockSize]                           The size of each block. Maximum is 100MB.
* @param {string}             [options.blockIdPrefix]                       The prefix to be used to generate the block id.
* @param {string}             [options.leaseId]                             The lease identifier.
* @param {string}             [options.transactionalContentMD5]             The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {int}                [options.parallelOperationThreadCount]        Parallel operation thread count.
* @param {bool}               [options.storeBlobContentMD5]                 Specifies whether the blob's ContentMD5 header should be set on uploads. 
*                                                                           The default value is false for page blobs and true for block blobs.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The blob's MD5 hash.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      `error` will contain information
*                                                                           if an error occurs; otherwise `[result]{@link BlobResult}` will contain
*                                                                           the blob information.
*                                                                           `response` will contain information related to this operation.
* @return {Stream}
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
* var stream = fs.createReadStream(fileNameTarget).pipe(blobService.createWriteStreamToBlockBlob(containerName, blobName, { blockIdPrefix: 'block' }));
*/
BlobService.prototype.createWriteStreamToBlockBlob = function (container, blob, optionsOrCallback, callback) {
  return this._createWriteStreamToBlob(container, blob, BlobConstants.BlobTypes.BLOCK, 0, false, optionsOrCallback, callback);
};
 
/**
* Creates a new block to be committed as part of a blob.
*
* @this {BlobService}
* @param {string}             blockId                                   The block identifier.
* @param {string}             container                                 The container name.
* @param {string}             blob                                      The blob name.
* @param {Stream}             readStream                                The read stream.
* @param {int}                streamLength                              The stream length.
* @param {object}             [options]                                 The request options.
* @param {bool}               [options.useTransactionalMD5]             Calculate and send/validate content MD5 for transactions.
* @param {string}             [options.leaseId]                         The target blob lease identifier.
* @param {string}             [options.transactionalContentMD5]         An MD5 hash of the block content. This hash is used to verify the integrity of the block during transport.
* @param {AccessConditions}   [options.accessConditions]                The access conditions.
* @param {LocationMode}       [options.locationMode]                    Specifies the location mode used to decide which location the request should be sent to. 
*                                                                       Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]             The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]        The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]        The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                       The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                       execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                 A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]               Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                       The default value is false.
* @param {errorOrResponse}    callback                                  `error` will contain information
*                                                                       if an error occurs; otherwise 
*                                                                       `response` will contain information related to this operation.
*/
BlobService.prototype.createBlockFromStream = function (blockId, container, blob, readStream, streamLength, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('createBlockFromStream', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.exists(readStream, 'readStream');
    v.value(streamLength, 'streamLength');
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
 
  if (streamLength > BlobConstants.MAX_BLOCK_BLOB_BLOCK_SIZE) {
    throw new RangeError(SR.INVALID_STREAM_LENGTH);
  } else {
    this._createBlock(blockId, container, blob, null, readStream, streamLength, options, callback);
  }
};
 
/**
* Creates a new block to be committed as part of a blob.
*
* @this {BlobService}
* @param {string}             blockId                                   The block identifier.
* @param {string}             container                                 The container name.
* @param {string}             blob                                      The blob name.
* @param {string|buffer}      content                                   The block content.
* @param {object}             [options]                                 The request options.
* @param {bool}               [options.useTransactionalMD5]             Calculate and send/validate content MD5 for transactions.
* @param {string}             [options.leaseId]                         The target blob lease identifier.
* @param {string}             [options.transactionalContentMD5]         An MD5 hash of the block content. This hash is used to verify the integrity of the block during transport. 
* @param {AccessConditions}   [options.accessConditions]                The access conditions.
* @param {LocationMode}       [options.locationMode]                    Specifies the location mode used to decide which location the request should be sent to. 
*                                                                       Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]             The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]        The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]        The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                       The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                       execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                 A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]               Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                       The default value is false.
* @param {errorOrResponse}    callback                                  `error` will contain information
*                                                                       if an error occurs; otherwise 
*                                                                       `response` will contain information related to this operation.
*/
BlobService.prototype.createBlockFromText = function (blockId, container, blob, content, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('createBlockFromText', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
  
  var options = extend(true, {}, userOptions);
  var contentLength = (Buffer.isBuffer(content) ? content.length : Buffer.byteLength(content));
 
  if (contentLength > BlobConstants.MAX_BLOCK_BLOB_BLOCK_SIZE) {
    throw new RangeError(SR.INVALID_TEXT_LENGTH);
  } else {
    this._createBlock(blockId, container, blob, content, null, contentLength, options, callback);
  }
};
 
/**
* Creates a new block to be committed as part of a block blob.
* @ignore
*
* @this {BlobService}
* @param {string}             blockId                                   The block identifier.
* @param {string}             container                                 The container name.
* @param {string}             blob                                      The blob name.
* @param {string|buffer}      content                                   The block content.
* @param (Stream)             stream                                    The stream to the data to store.
* @param {int}                length                                    The length of the stream or text to upload.
* @param {object}             [options]                                 The request options.
* @param {bool}               [options.useTransactionalMD5]             Calculate and send/validate content MD5 for transactions.
* @param {string}             [options.leaseId]                         The target blob lease identifier.
* @param {string}             [options.transactionalContentMD5]         An MD5 hash of the block content. This hash is used to verify the integrity of the block during transport.
* @param {AccessConditions}   [options.accessConditions]                The access conditions.
* @param {LocationMode}       [options.locationMode]                    Specifies the location mode used to decide which location the request should be sent to. 
*                                                                       Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]             The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]        The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]        The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                       The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                       execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                 A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]               Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                       The default value is false.
* @param {errorOrResponse}    callback                                  `error` will contain information
*                                                                       if an error occurs; otherwise 
*                                                                       `response` will contain information related to this operation.
*/
BlobService.prototype._createBlock = function (blockId, container, blob, content, stream, length, options, callback) {
  var resourceName = createResourceName(container, blob);
 
  var self = this;
  var startCreateBlock = function () {
    var webResource = WebResource.put(resourceName)
      .withQueryOption(QueryStringConstants.COMP, 'block')
      .withQueryOption(QueryStringConstants.BLOCK_ID, new Buffer(blockId).toString('base64'))
      .withHeader(HeaderConstants.CONTENT_LENGTH, length);
 
    BlobResult.setHeadersFromBlob(webResource, options);
 
    var processResponseCallback = function (responseObject, next) {
      var finalCallback = function (returnObject) {
        callback(returnObject.error, returnObject.response);
      };
 
      next(responseObject, finalCallback);
    };
 
    if (!azureutil.objectIsNull(content)) {
      self.performRequest(webResource, content, options, processResponseCallback);
    } else {
      self.performRequestOutputStream(webResource, stream, options, processResponseCallback);
    }
  }; 
  
  if (azureutil.objectIsNull(options.transactionalContentMD5) && options.useTransactionalMD5) {
    if (!azureutil.objectIsNull(content)) {
      options.transactionalContentMD5 = azureutil.getContentMd5(content);
      startCreateBlock();
    } else {
      azureutil.calculateMD5(stream, length, options, function (internalBuff, contentMD5) {
        options.transactionalContentMD5 = contentMD5;
        content = internalBuff;
        length = internalBuff.length;
        startCreateBlock();
      });
    }
  } else {
    startCreateBlock();
  }
};
 
/**
* Writes a blob by specifying the list of block IDs that make up the blob.
* In order to be written as part of a blob, a block must have been successfully written to the server in a prior
* createBlock operation.
*
* @this {BlobService}
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param {object}             blockList                                     The block identifiers.
* @param {object}             [options]                                     The request options.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {string}             [options.leaseId]                             The target blob lease identifier.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The blob's MD5 hash.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      `error` will contain information
*                                                                           if an error occurs; otherwise `[result]{@link BlobResult}` will contain
*                                                                           the blob information.
*                                                                           `response` will contain information related to this operation.
*/
BlobService.prototype.commitBlocks = function (container, blob, blockList, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('commitBlocks', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var blockListXml = BlockListResult.serialize(blockList);
 
  var resourceName = createResourceName(container, blob);
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.put(resourceName)
    .withQueryOption(QueryStringConstants.COMP, 'blocklist')
    .withHeader(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(blockListXml))
    .withBody(blockListXml);
 
  BlobResult.setPropertiesFromBlob(webResource, options);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.blobResult = new BlobResult(container, blob);
    responseObject.blobResult.list = null;
    if (!responseObject.error) {
      responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
      responseObject.blobResult.list = blockList;
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.blobResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, webResource.body, options, processResponseCallback);
};
 
/**
* Retrieves the list of blocks that have been uploaded as part of a block blob.
*
* @this {BlobService}
* @param {string}             container                                   The container name.
* @param {string}             blob                                        The blob name.
* @param {BlockListFilter}    blocklisttype                               The type of block list to retrieve.
* @param {object}             [options]                                   The request options.
* @param {string}             [options.snapshotId]                        The source blob snapshot identifier.
* @param {string}             [options.leaseId]                           The target blob lease identifier.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `result` will contain
*                                                                         the blocklist information.
*                                                                         `response` will contain information related to this operation.
*/
BlobService.prototype.listBlocks = function (container, blob, blocklisttype, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('listBlocks', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var resourceName = createResourceName(container, blob);
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.get(resourceName)
    .withQueryOption(QueryStringConstants.COMP, 'blocklist')
    .withQueryOption(QueryStringConstants.BLOCK_LIST_TYPE, blocklisttype)
    .withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId);
 
  options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY;
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.blockListResult = null;
    if (!responseObject.error) {
      responseObject.blockListResult = BlockListResult.parse(responseObject.response.body.BlockList);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.blockListResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Generate a random block id prefix
*/
BlobService.prototype.generateBlockIdPrefix = function () {
  var prefix = Math.floor(Math.random() * 0x100000000).toString(16);
  return azureutil.zeroPaddingString(prefix, 8);
};
 
/**
* Get a block id according to prefix and block number
*/
BlobService.prototype.getBlockId = function (prefix, number) {
  return prefix + '-' + azureutil.zeroPaddingString(number, 6);
};
 
// Append blob methods
 
/**
* Creates an empty append blob. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
*
* @this {BlobService}
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param {object}             [options]                                     The request options.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {string}             [options.leaseId]                             The target blob lease identifier.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The blob's MD5 hash.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResponse}    callback                                      `error` will contain information
*                                                                           if an error occurs; otherwise 
*                                                                           `response` will contain information related to this operation.
*/
BlobService.prototype.createOrReplaceAppendBlob = function (container, blob, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  
  validate.validateArgs('createOrReplaceAppendBlob', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
  
  var options = extend(true, {}, userOptions);
  
  var resourceName = createResourceName(container, blob);
  
  var webResource = WebResource.put(resourceName)
    .withHeader(HeaderConstants.BLOB_TYPE, BlobConstants.BlobTypes.APPEND)
    .withHeader(HeaderConstants.LEASE_ID, options.leaseId)
    .withHeader(HeaderConstants.CONTENT_LENGTH, 0);
 
  BlobResult.setHeadersFromBlob(webResource, options);
  
  var processResponseCallback = function (responseObject, next) {
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.response);
    };
    
    next(responseObject, finalCallback);
  };
  
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Creates a new append blob from a local file. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks.
* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you.
* If you want to append data to an already existing blob, please look at appendFromLocalFile.
* (Not recommended for use in the JavaScript Client Library)
*
* @this {BlobService}
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param {string}             localFileName                                 The local path to the file to be uploaded.
* @param {object}             [options]                                     The request options.
* @param {bool}               [options.absorbConditionalErrorsOnRetry]      Specifies whether to absorb the conditional error on retry.
* @param {string}             [options.leaseId]                             The lease identifier. 
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {bool}               [options.storeBlobContentMD5]                 Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The blob's MD5 ahash.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      `error` will contain information
*                                                                           if an error occurs; otherwise `[result]{@link BlobResult}` will contain
*                                                                           the blob information.
*                                                                           `response` will contain information related to this operation.
* @return {SpeedSummary}
*/
BlobService.prototype.createAppendBlobFromLocalFile = function (container, blob, localFileName, optionsOrCallback, callback) {
  return this._createBlobFromLocalFile(container, blob, BlobConstants.BlobTypes.APPEND, localFileName, optionsOrCallback, callback);
};
 
/**
* Uploads an append blob from a stream. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks.
* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you.
* If you want to append data to an already existing blob, please look at appendFromStream.
*
* @this {BlobService}
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param (Stream)             stream                                        Stream to the data to store.
* @param {int}                streamLength                                  The length of the stream to upload.
* @param {object}             [options]                                     The request options.
* @param {bool}               [options.absorbConditionalErrorsOnRetry]      Specifies whether to absorb the conditional error on retry.
* @param {SpeedSummary}       [options.speedSummary]                        The download tracker objects.
* @param {string}             [options.leaseId]                             The lease identifier. 
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {bool}               [options.storeBlobContentMD5]                 Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The blob's MD5 hash.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      `error` will contain information
*                                                                           if an error occurs; otherwise `[result]{@link BlobResult}` will contain
*                                                                           the blob information.
*                                                                           `response` will contain information related to this operation.
* @return {SpeedSummary}
*/
BlobService.prototype.createAppendBlobFromStream = function (container, blob, stream, streamLength, optionsOrCallback, callback) {
  return this._createBlobFromStream(container, blob, BlobConstants.BlobTypes.APPEND, stream, streamLength, optionsOrCallback, callback);
};
 
/**
* Uploads an append blob from a text string. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks.
* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you.
* If you want to append data to an already existing blob, please look at appendFromText.
*
* @this {BlobService}
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param {string|object}      text                                          The blob text, as a string or in a Buffer.
* @param {object}             [options]                                     The request options.
* @param {bool}               [options.absorbConditionalErrorsOnRetry]      Specifies whether to absorb the conditional error on retry.
* @param {string}             [options.leaseId]                             The lease identifier. 
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {bool}               [options.storeBlobContentMD5]                 Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The blob's MD5 hash.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      `error` will contain information
*                                                                           if an error occurs; otherwise `[result]{@link BlobResult}` will contain
*                                                                           the blob information.
*                                                                           `response` will contain information related to this operation.
*/
BlobService.prototype.createAppendBlobFromText = function (container, blob, text, optionsOrCallback, callback) {
  return this._createBlobFromText(container, blob, BlobConstants.BlobTypes.APPEND, text, optionsOrCallback, callback);
};
 
/**
* Provides a stream to write to a new append blob. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks.
* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you.
*
* @this {BlobService}
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param {object}             [options]                                     The request options.
* @param {bool}               [options.absorbConditionalErrorsOnRetry]      Specifies whether to absorb the conditional error on retry.
* @param {string}             [options.leaseId]                             The lease identifier.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {bool}               [options.storeBlobContentMD5]                 Specifies whether the blob's ContentMD5 header should be set on uploads. 
*                                                                           The default value is false for page blobs and true for block blobs.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The blob's MD5 hash.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResponse}    callback                                      The callback function.
* @return {Stream}
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
* var stream = fs.createReadStream(fileNameTarget).pipe(blobService.createWriteStreamToAppendBlob(containerName, blobName));
*/
BlobService.prototype.createWriteStreamToNewAppendBlob = function (container, blob, optionsOrCallback, callback) {
  return this._createWriteStreamToBlob(container, blob, BlobConstants.BlobTypes.APPEND, 0, true, optionsOrCallback, callback);
};
 
/**
* Provides a stream to write to an existing append blob. Assumes that the blob exists. 
* If it does not, please create the blob using createAppendBlob before calling this method or use createWriteStreamToNewAppendBlob.
* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks.
* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you.
*
* @this {BlobService}
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param {object}             [options]                                     The request options.
* @param {bool}               [options.absorbConditionalErrorsOnRetry]      Specifies whether to absorb the conditional error on retry.
* @param {string}             [options.leaseId]                             The lease identifier.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {bool}               [options.storeBlobContentMD5]                 Specifies whether the blob's ContentMD5 header should be set on uploads. 
*                                                                           The default value is false for page blobs and true for block blobs.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The blob's MD5 hash.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResponse}    callback                                      The callback function.
* @return {Stream}
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
* var stream = fs.createReadStream(fileNameTarget).pipe(blobService.createWriteStreamToAppendBlob(containerName, blobName));
*/
BlobService.prototype.createWriteStreamToExistingAppendBlob = function (container, blob, optionsOrCallback, callback) {
  return this._createWriteStreamToBlob(container, blob, BlobConstants.BlobTypes.APPEND, 0, false, optionsOrCallback, callback);
};
 
/**
* Appends to an append blob from a local file. Assumes the blob already exists on the service.
* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks.
* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you.
* (Not recommended for use in the JavaScript Client Library)
*
* @this {BlobService}
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param {string}             localFileName                                 The local path to the file to be uploaded.
* @param {object}             [options]                                     The request options.
* @param {bool}               [options.absorbConditionalErrorsOnRetry]      Specifies whether to absorb the conditional error on retry.
* @param {string}             [options.leaseId]                             The lease identifier.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The blob's MD5 hash.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      `error` will contain information
*                                                                           if an error occurs; otherwise `[result]{@link BlobResult}` will contain
*                                                                           the blob information.
*                                                                           `response` will contain information related to this operation.
* @return {SpeedSummary}
*/
BlobService.prototype.appendFromLocalFile = function (container, blob, localFileName, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  
  validate.validateArgs('appendFromLocalFile', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.string(localFileName, 'localFileName');
    v.callback(callback);
  });
  
  var options = extend(true, {}, userOptions);  
 
  var self = this;
  fs.stat(localFileName, function (error, stat) {
    if (error) {
      callback(error);
    } else {
      var stream = new FileReadStream(localFileName, { calcContentMd5: options.storeBlobContentMD5 });
      var streamCallback = function (appendError, blob, response) {
        if (azureutil.objectIsFunction(stream.destroy)) {
          stream.destroy();
        }
        callback(appendError, blob, response);
      };
      self._uploadBlobFromStream(false, container, blob, BlobConstants.BlobTypes.APPEND, stream, stat.size, options, streamCallback);
    }
  });
  
  return  options.speedSummary;
};
 
/**
* Appends to an append blob from a stream. Assumes the blob already exists on the service.
* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks.
* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you.
*
* @this {BlobService}
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param (Stream)             stream                                        Stream to the data to store.
* @param {int}                streamLength                                  The length of the stream to upload.
* @param {object}             [options]                                     The request options.
* @param {bool}               [options.absorbConditionalErrorsOnRetry]      Specifies whether to absorb the conditional error on retry.
* @param {SpeedSummary}       [options.speedSummary]                        The download tracker objects.
* @param {string}             [options.leaseId]                             The lease identifier.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The blob's MD5 hash.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      `error` will contain information
*                                                                           if an error occurs; otherwise `[result]{@link BlobResult}` will contain
*                                                                           the blob information.
*                                                                           `response` will contain information related to this operation.
* @return {SpeedSummary}
*/
BlobService.prototype.appendFromStream = function (container, blob, stream, streamLength, optionsOrCallback, callback) {
  var options;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; });
  
  validate.validateArgs('appendFromStream', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.exists(stream, 'stream');
    v.value(streamLength, 'streamLength');
    v.callback(callback);
  });
 
  return this._uploadBlobFromStream(false, container, blob, BlobConstants.BlobTypes.APPEND, stream, streamLength, options, callback);
};
 
/**
* Appends to an append blob from a text string. Assumes the blob already exists on the service.
* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks.
* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you.
*
* @this {BlobService}
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param {string|object}      text                                          The blob text, as a string or in a Buffer.
* @param {object}             [options]                                     The request options.
* @param {bool}               [options.absorbConditionalErrorsOnRetry]      Specifies whether to absorb the conditional error on retry.
* @param {string}             [options.leaseId]                             The lease identifier.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {bool}               [options.storeBlobContentMD5]                 Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The blob's MD5 hash.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      `error` will contain information
*                                                                           if an error occurs; otherwise `[result]{@link BlobResult}` will contain
*                                                                           the blob information.
*                                                                           `response` will contain information related to this operation.
*/
BlobService.prototype.appendFromText = function (container, blob, text, optionsOrCallback, callback) {
  return this._uploadBlobFromText(false, container, blob, BlobConstants.BlobTypes.APPEND, text, optionsOrCallback, callback);
};
 
 
/**
* Creates a new block from a read stream to be appended to an append blob.
* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks.
* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you.
*
* @this {BlobService}
* @param {string}             container                                 The container name.
* @param {string}             blob                                      The blob name.
* @param {Stream}             readStream                                The read stream.
* @param {int}                streamLength                              The stream length.
* @param {object}             [options]                                 The request options.
* @param {bool}               [options.absorbConditionalErrorsOnRetry]  Specifies whether to absorb the conditional error on retry.
* @param {int}                [options.maxBlobSize]                     The max length in bytes allowed for the append blob to grow to.
* @param {int}                [options.appendPosition]                  The number indicating the byte offset to check for. The append will succeed only if the end position of the blob is equal to this number.
* @param {string}             [options.leaseId]                         The target blob lease identifier.
* @param {string}             [options.transactionalContentMD5]         An MD5 hash of the block content. This hash is used to verify the integrity of the block during transport.
* @param {AccessConditions}   [options.accessConditions]                The access conditions.
* @param {LocationMode}       [options.locationMode]                    Specifies the location mode used to decide which location the request should be sent to. 
*                                                                       Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]             The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]        The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]        The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                       The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                       execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                 A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]               Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                       The default value is false.
* @param {errorOrResult}      callback                                  `error` will contain information
*                                                                      if an error occurs; otherwise `[result]{@link BlobResult}` will contain
*                                                                      the blob information.
*                                                                      `response` will contain information related to this operation.
*/
BlobService.prototype.appendBlockFromStream = function (container, blob, readStream, streamLength, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  
  validate.validateArgs('appendBlockFromStream', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.exists(readStream, 'readStream');
    v.value(streamLength, 'streamLength');
    v.callback(callback);
  });
  
  var options = extend(true, {}, userOptions);
  
  if (streamLength > BlobConstants.MAX_APPEND_BLOB_BLOCK_SIZE) {
    throw new RangeError(SR.INVALID_STREAM_LENGTH);
  } else {
    this._appendBlock(container, blob, null, readStream, streamLength, options, callback);
  }
};
 
/**
* Creates a new block from a text to be appended to an append blob.
* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks.
* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you.
*
* @this {BlobService}
* @param {string}             container                                 The container name.
* @param {string}             blob                                      The blob name.
* @param {string|object}      content                                   The block text, as a string or in a Buffer.
* @param {object}             [options]                                 The request options.
* @param {bool}               [options.absorbConditionalErrorsOnRetry]  Specifies whether to absorb the conditional error on retry.
* @param {int}                [options.maxBlobSize]                     The max length in bytes allowed for the append blob to grow to.
* @param {int}                [options.appendPosition]                  The number indicating the byte offset to check for. The append will succeed only if the end position of the blob is equal to this number.
* @param {string}             [options.leaseId]                         The target blob lease identifier.
* @param {string}             [options.transactionalContentMD5]         An MD5 hash of the block content. This hash is used to verify the integrity of the block during transport.
* @param {AccessConditions}   [options.accessConditions]                The access conditions.
* @param {LocationMode}       [options.locationMode]                    Specifies the location mode used to decide which location the request should be sent to. 
*                                                                       Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]             The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]        The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]        The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                       The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                       execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                 A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]               Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                       The default value is false.
* @param {errorOrResponse}    callback                                  `error` will contain information
*                                                                       if an error occurs; otherwise 
*                                                                       `response` will contain information related to this operation.
*/
BlobService.prototype.appendBlockFromText = function (container, blob, content, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  
  validate.validateArgs('appendBlockFromText', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var contentLength = (Buffer.isBuffer(content) ? content.length : Buffer.byteLength(content));
  if (contentLength > BlobConstants.MAX_APPEND_BLOB_BLOCK_SIZE) {
    throw new RangeError(SR.INVALID_TEXT_LENGTH);
  } else {
    this._appendBlock(container, blob, content, null, contentLength, options, callback);
  }
};
 
// Private methods
 
/**
* Creates a new blob (Block/Page/Append). If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
*
* @ignore
*
* @this {BlobService}
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param {BlobType}           blobType                                      The blob type.
* @param {string}             localFileName                                 The local path to the file to be uploaded.
* @param {object}             [options]                                     The request options.
* @param {bool}               [options.absorbConditionalErrorsOnRetry]      Specifies whether to absorb the conditional error on retry. (For append blob only)
* @param {int}                [options.blockSize]                           The size of each block. Maximum is 100MB.
* @param {string}             [options.blockIdPrefix]                       The prefix to be used to generate the block id. (For block blob only)
* @param {string}             [options.leaseId]                             The lease identifier.
* @param {string}             [options.transactionalContentMD5]             An MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {int}                [options.parallelOperationThreadCount]        Parallel operation thread count.
* @param {bool}               [options.storeBlobContentMD5]                 Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The MD5 hash of the blob content.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      The callback function.
*
* @return {SpeedSummary}
*
*/
BlobService.prototype._createBlobFromLocalFile = function (container, blob, blobType, localFileName, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  
  validate.validateArgs('_createBlobFromLocalFile', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.blobTypeIsValid(blobType);
    v.string(localFileName, 'localFileName');
    v.callback(callback);
  });
  
  var options = extend(true, {}, userOptions);
  options.speedSummary = options.speedSummary || new SpeedSummary(blob);
 
  var self = this;
  var size = 0;
  
  var creationCallback = function (createError, createBlob, createResponse) {
    if (createError) {
      callback(createError, createBlob, createResponse);
    } else {
      // Automatically detect the mime type
      if(azureutil.tryGetValueChain(options, ['contentSettings','contentType'], undefined) === undefined) {
        azureutil.setObjectInnerPropertyValue(options, ['contentSettings','contentType'], mime.lookup(localFileName));
      }
 
      var stream = new FileReadStream(localFileName, { calcContentMd5: options.storeBlobContentMD5 });
      var streamCallback = function (createError, createBlob, createResponse) {
        if (azureutil.objectIsFunction(stream.destroy)) {
          stream.destroy();
        }
        callback(createError, createBlob, createResponse);
      };
      self._uploadBlobFromStream(true, container, blob, blobType, stream, size, options, streamCallback);
    }
  };
 
  // Check the file size to determine the upload method: single request or chunks
  fs.stat(localFileName, function (error, stat) {
    if (error) {
      callback(error);
    } else {
      size = stat.size;
      self._createBlob(container, blob, blobType, size, options, creationCallback);
    }
  });
  
  return options.speedSummary;
};
 
/**
* Creates a new blob from a stream. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
*
* @ignore
*
* @this {BlobService}
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param {BlobType}           blobType                                      The blob type.
* @param (Stream)             stream                                        Stream to the data to store.
* @param {int}                streamLength                                  The length of the stream to upload.
* @param {object}             [options]                                     The request options.
* @param {SpeedSummary}       [options.speedSummary]                        The upload tracker objects.
* @param {bool}               [options.absorbConditionalErrorsOnRetry]      Specifies whether to absorb the conditional error on retry. (For append blob only)
* @param {string}             [options.blockIdPrefix]                       The prefix to be used to generate the block id. (For block blob only)
* @param {string}             [options.leaseId]                             The lease identifier.
* @param {string}             [options.transactionalContentMD5]             The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {int}                [options.parallelOperationThreadCount]        Parallel operation thread count.
* @param {bool}               [options.storeBlobContentMD5]                 Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The blob's MD5 hash.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      The callback function.
* @return {SpeedSummary}
*/
BlobService.prototype._createBlobFromStream = function (container, blob, blobType, stream, streamLength, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  
  validate.validateArgs('_createBlobFromStream', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.blobTypeIsValid(blobType);
    v.exists(stream, 'stream');
    v.value(streamLength, 'streamLength');
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
 
  var self = this;
  var creationCallback = function (createError, createBlob, createResponse) {
    if (createError) {
      callback(createError, createBlob, createResponse);
    } else {
      self._uploadBlobFromStream(true, container, blob, blobType, stream, streamLength, options, callback);
    }
  };  
 
  this._createBlob(container, blob, blobType, streamLength, options, creationCallback);
 
  return options.speedSummary;
};
 
/**
* Uploads a block blob or an append blob from a text string. If the blob already exists on the service, it will be overwritten.
* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object.
*
* @ignore
* 
* @this {BlobService}
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param {BlobType}           blobType                                      The blob type.
* @param {string|buffer}      content                                       The blob text, as a string or in a Buffer.
* @param {object}             [options]                                     The request options.
* @param {bool}               [options.absorbConditionalErrorsOnRetry]      Specifies whether to absorb the conditional error on retry. (For append blob only)
* @param {string}             [options.leaseId]                             The lease identifier.
* @param {string}             [options.transactionalContentMD5]             The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {bool}               [options.storeBlobContentMD5]                 Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The blob's MD5 hash.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      `error` will contain information
*                                                                           if an error occurs; otherwise `result` will contain
*                                                                           information about the blob.
*                                                                           `response` will contain information related to this operation.
*/
BlobService.prototype._createBlobFromText = function (container, blob, blobType, content, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  
  validate.validateArgs('_createBlobFromText', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.blobTypeIsValid(blobType);
    v.callback(callback);
  });
  
  var options = extend(true, {}, userOptions);
 
  var self = this;
  var creationCallback = function (createError, createBlob, createResponse) {
    if (createError) {
      callback(createError, createBlob, createResponse);
    } else {
      self._uploadBlobFromText(true, container, blob, blobType, content, options, callback);
    }
  };
 
  var contentLength = azureutil.objectIsNull(content) ? 0 : ((Buffer.isBuffer(content) ? content.length : Buffer.byteLength(content)));
  this._createBlob(container, blob, blobType, contentLength, options, creationCallback);
 
  return options.speedSummary; 
};
 
/**
* Provides a stream to write to a block blob or an append blob.
*
* @ignore
* 
* @this {BlobService}
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param {BlobType}           blobType                                      The blob type.
* @param {int}                length                                        The blob length.
* @param {bool}               createNewBlob                                 Specifies whether create a new blob.
* @param {object}             [options]                                     The request options.
* @param {bool}               [options.absorbConditionalErrorsOnRetry]      Specifies whether to absorb the conditional error on retry. (For append blob only)
* @param {string}             [options.blockSize]                           The size of each block. Maximum is 100MB. (For block blob only)
* @param {string}             [options.blockIdPrefix]                       The prefix to be used to generate the block id. (For block blob only)
* @param {string}             [options.leaseId]                             The lease identifier.
* @param {string}             [options.transactionalContentMD5]             The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {int}                [options.parallelOperationThreadCount]        Parallel operation thread count.
* @param {bool}               [options.storeBlobContentMD5]                 Specifies whether the blob's ContentMD5 header should be set on uploads. 
*                                                                           The default value is false for page blobs and true for block blobs.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The blob's MD5 hash.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResponse}    callback                                      The callback function.
* @return {Stream}
*/
BlobService.prototype._createWriteStreamToBlob = function (container, blob, blobType, length, createNewBlob, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  
  validate.validateArgs('_createWriteStreamToBlob', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.blobTypeIsValid(blobType);
  });
 
  var options = extend(true, {}, userOptions);
  
  var sizeLimitation;
  if (blobType === BlobConstants.BlobTypes.BLOCK) {
    // default to true, unless explicitly set to false
    options.storeBlobContentMD5 = options.storeBlobContentMD5 === false ? false : true;
    sizeLimitation = options.blockSize || BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES;
  } else if (blobType == BlobConstants.BlobTypes.PAGE) {
    sizeLimitation = BlobConstants.DEFAULT_WRITE_PAGE_SIZE_IN_BYTES;
  } else if (blobType == BlobConstants.BlobTypes.APPEND) {
    sizeLimitation = BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES;
  }
  
  var stream = new ChunkStream({ calcContentMd5: options.storeBlobContentMD5 });
  stream._highWaterMark = sizeLimitation;
 
  stream.pause(); //Immediately pause the stream in order to wait for the destination to getting ready
 
  var self = this;
  var createCallback = function (createError, createBlob, createResponse) {
    if (createError) {
      if (callback) {
        callback(createError, createBlob, createResponse);
      }
    } else {
      self._uploadBlobFromStream(createNewBlob, container, blob, blobType, stream, null, options, function (error, blob, response) {
        if (error) {
          stream.emit('error', error);
        }
        
        if (callback) {
          callback(error, blob, response);
        }
      });
    }
  };
 
  if (createNewBlob === true) {
    this._createBlob(container, blob, blobType, length, options, createCallback);
  } else {
    createCallback();
  }
  
  return stream;
};
 
/**
* Upload blob content from a stream. Assumes the blob already exists.
*
* @ignore
*
* @this {BlobService}
* @param {bool}               isNewBlob                                     Specifies whether the blob is newly created.
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param {BlobType}           blobType                                      The blob type.
* @param (Stream)             stream                                        Stream to the data to store.
* @param {int}                streamLength                                  The length of the stream to upload.
* @param {object}             [options]                                     The request options.
* @param {SpeedSummary}       [options.speedSummary]                        The upload tracker objects.
* @param {bool}               [options.absorbConditionalErrorsOnRetry]      Specifies whether to absorb the conditional error on retry. (For append blob only)
* @param {string}             [options.blockIdPrefix]                       The prefix to be used to generate the block id. (For block blob only)
* @param {int}                [options.blockSize]                           The size of each block. Maximum is 100MB. (For block blob only)
* @param {string}             [options.leaseId]                             The lease identifier.
* @param {string}             [options.transactionalContentMD5]             The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {int}                [options.parallelOperationThreadCount]        Parallel operation thread count.
* @param {bool}               [options.storeBlobContentMD5]                 Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The blob's MD5 hash.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      The callback function.
* @return {SpeedSummary}
*/
BlobService.prototype._uploadBlobFromStream = function (isNewBlob, container, blob, blobType, stream, streamLength, optionsOrCallback, callback) {
  var options;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; });
  options.speedSummary = options.speedSummary || new SpeedSummary(blob);
 
  if (blobType === BlobConstants.BlobTypes.BLOCK) {
    // default to true, unless explicitly set to false
    options.storeBlobContentMD5 = options.storeBlobContentMD5 === false ? false : true;
  }
 
  stream.pause();
 
  var self = this;
  var startUpload = function () {
    var putBlockBlobFromStream = function () {
      var finalCallback = function (error, result, response) {
        if (error) {
          callback(error, result, response);
        } else {
          callback(error, result, response);
        }
      };
 
      if (streamLength > 0 && azureutil.objectIsNull(azureutil.tryGetValueChain(options, ['contentSettings', 'contentMD5'], null)) && options.storeBlobContentMD5) {
        azureutil.calculateMD5(stream, Math.min(self.singleBlobPutThresholdInBytes, streamLength), options, function (internalBuff, contentMD5) {
          azureutil.setObjectInnerPropertyValue(options, ['contentSettings', 'contentMD5'], contentMD5);
          self._putBlockBlob(container, blob, internalBuff, null, internalBuff.length, options, finalCallback);
        });
        stream.resume();
      } else {
        // Stream will resume when it has a pipe destination or a 'data' listener
        self._putBlockBlob(container, blob, null, stream, streamLength, options, finalCallback);
      }
    };
 
    if (streamLength === null || streamLength >= self.singleBlobPutThresholdInBytes || blobType !== BlobConstants.BlobTypes.BLOCK) {
      var chunkStream = new ChunkStreamWithStream(stream, { calcContentMd5: options.storeBlobContentMD5 });
      self._uploadContentFromChunkStream(container, blob, blobType, chunkStream, streamLength, options, callback);
    } else {
      putBlockBlobFromStream();
    }
  };
 
  if (!isNewBlob) {
    if (options.storeBlobContentMD5 && blobType !== BlobConstants.BlobTypes.BLOCK ) {
      throw new Error(SR.MD5_NOT_POSSIBLE);
    }
 
    if (blobType === BlobConstants.BlobTypes.APPEND || options.accessConditions) {
      // Do a getBlobProperties right at the beginning for existing blobs and use the user passed in access conditions. 
      // So any pre-condition failure on the first block (in a strictly single writer scenario) is caught.
      // This call also helps us get the append position to append to if the user hasn’t specified an access condition.
      this.getBlobProperties(container, blob, options, function (error, properties, response) {
        if (error && !(options.accessConditions && options.accessConditions.EtagNonMatch === '*' && response.statusCode === 400)) {
          callback(error);
        } else {
          if (blobType === BlobConstants.BlobTypes.APPEND) {
            options.appendPosition = properties.contentLength;
          }
 
          startUpload();
        }
      });
    } else {
      startUpload();
    }
  } else {
    startUpload();
  }
 
  return  options.speedSummary;
};
 
/**
* Upload blob content from a text. Assumes the blob already exists.
*
* @ignore
*
* @this {BlobService}
* @param {bool}               isNewBlob                                     Specifies whether the blob is newly created.
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param {BlobType}           blobType                                      The blob type.
* @param (string)             content                                       The blob text, as a string or in a Buffer.
* @param {object}             [options]                                     The request options.
* @param {SpeedSummary}       [options.speedSummary]                        The upload tracker objects.
* @param {bool}               [options.absorbConditionalErrorsOnRetry]      Specifies whether to absorb the conditional error on retry. (For append blob only)
* @param {string}             [options.blockIdPrefix]                       The prefix to be used to generate the block id. (For block blob only)
* @param {string}             [options.leaseId]                             The lease identifier.
* @param {string}             [options.transactionalContentMD5]             The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {int}                [options.parallelOperationThreadCount]        Parallel operation thread count.
* @param {bool}               [options.storeBlobContentMD5]                 Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The blob's MD5 hash.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      The callback function.
* @return {SpeedSummary}
*/
BlobService.prototype._uploadBlobFromText = function (isNewBlob, container, blob, blobType, content, optionsOrCallback, callback) {
  var options;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; });
  options.speedSummary = options.speedSummary || new SpeedSummary(blob);
  options[HeaderConstants.CONTENT_TYPE] = (options.contentSettings && options.contentSettings.contentType) || 'text/plain;charset="utf-8"';
 
  var self = this;
  var startUpload = function () {
    var operationFunc;
    var length = azureutil.objectIsNull(content) ? 0 : (Buffer.isBuffer(content) ? content.length : Buffer.byteLength(content));
 
    if (blobType === BlobConstants.BlobTypes.BLOCK) {
      // default to true, unless explicitly set to false
      options.storeBlobContentMD5 = options.storeBlobContentMD5 === false ? false : true;
      operationFunc = self._putBlockBlob;
 
      if (length > BlobConstants.MAX_SINGLE_UPLOAD_BLOB_SIZE_IN_BYTES) {
        throw new RangeError(SR.INVALID_BLOB_LENGTH);
      }
    } else if (blobType === BlobConstants.BlobTypes.APPEND) {
      operationFunc = self._appendBlock;
 
      if (length > BlobConstants.MAX_APPEND_BLOB_BLOCK_SIZE) {
        throw new RangeError(SR.INVALID_TEXT_LENGTH);
      }
    }
 
    var finalCallback = function (error, blobResult, response) {
      if (blobType !== BlobConstants.BlobTypes.BLOCK) {
        self.setBlobProperties(container, blob, options.contentSettings, function (error, blob, response) {
          blob = extend(false, blob, blobResult);
          callback(error, blob, response);
        });
      } else {
        callback(error, blobResult, response);
      }
    };
 
    operationFunc.call(self, container, blob, content, null, length, options, finalCallback);
  };
 
  if (!isNewBlob) {
    if (options.storeBlobContentMD5 && blobType !== BlobConstants.BlobTypes.BLOCK ) {
      throw new Error(SR.MD5_NOT_POSSIBLE);
    }
 
    if (blobType === BlobConstants.BlobTypes.APPEND || options.accessConditions) {
      // Do a getBlobProperties right at the beginning for existing blobs and use the user passed in access conditions. 
      // So any pre-condition failure on the first block (in a strictly single writer scenario) is caught.
      // This call also helps us get the append position to append to if the user hasn’t specified an access condition.
      this.getBlobProperties(container, blob, options, function (error, properties) {
        if (error) {
          callback(error);
        } else {
          if (blobType === BlobConstants.BlobTypes.APPEND) {
            options.appendPosition = properties.contentLength;
          }
 
          startUpload();
        }
      });
    }    
  } else {
    if (!azureutil.objectIsNull(content) && azureutil.objectIsNull(azureutil.tryGetValueChain(options, ['contentSettings', 'contentMD5'], null)) && options.storeBlobContentMD5) {
      azureutil.setObjectInnerPropertyValue(options, ['contentSettings', 'contentMD5'], azureutil.getContentMd5(content));
    }
    startUpload();
  } 
};
 
/**
* Uploads a block blob from a stream.
* @ignore
*
* @this {BlobService}
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param {string}             text                                          The blob text.
* @param (Stream)             stream                                        Stream to the data to store.
* @param {int}                length                                        The length of the stream or text to upload.
* @param {object}             [options]                                     The request options.
* @param {string}             [options.leaseId]                             The lease identifier.
* @param {string}             [options.transactionalContentMD5]             The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {bool}               [options.storeBlobContentMD5]                 Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The blob's MD5 hash.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      `error` will contain information
*                                                                           if an error occurs; otherwise `result` will contain
*                                                                           information about the blob.
*                                                                           `response` will contain information related to this operation.
*/
BlobService.prototype._putBlockBlob = function (container, blob, text, stream, length, options, callback) {
  if (!options.speedSummary) {
    options.speedSummary = new SpeedSummary(blob);
  }
 
  var speedSummary = options.speedSummary;
  speedSummary.totalSize = length;
 
  var resourceName = createResourceName(container, blob);
  var webResource = WebResource.put(resourceName)
    .withHeader(HeaderConstants.CONTENT_TYPE, 'application/octet-stream')
    .withHeader(HeaderConstants.BLOB_TYPE, BlobConstants.BlobTypes.BLOCK)
    .withHeader(HeaderConstants.CONTENT_LENGTH, length);
 
  if (!azureutil.objectIsNull(text) && azureutil.objectIsNull(options.transactionalContentMD5) && options.useTransactionalMD5) {
    options.transactionalContentMD5 = azureutil.getContentMd5(text);
  }
 
  BlobResult.setHeadersFromBlob(webResource, options);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.blobResult = null;
    if (!responseObject.error) {
      responseObject.blobResult = new BlobResult(container, blob);
      responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
      if (options.metadata) {
        responseObject.blobResult.metadata = options.metadata;
      }
    }
 
    var finalCallback = function (returnObject) {
      if (!returnObject || !returnObject.error) {
        speedSummary.increment(length);
      }
      callback(returnObject.error, returnObject.blobResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  if (!azureutil.objectIsNull(text)) {
    this.performRequest(webResource, text, options, processResponseCallback);
  } else {
    this.performRequestOutputStream(webResource, stream, options, processResponseCallback);
  }
 
  return options.speedSummary;
};
 
/**
* Appends a new block to an append blob.
* 
* @ignore
*
* @this {BlobService}
* @param {string}             container                                 The container name.
* @param {string}             blob                                      The blob name.
* @param {string|buffer}      content                                   The block content.
* @param (Stream)             stream                                    The stream to the data to store.
* @param {int}                length                                    The length of the stream or content to upload.
* @param {object}             [options]                                 The request options.
* @param {bool}               [options.absorbConditionalErrorsOnRetry]  Specifies whether to absorb the conditional error on retry.
* @param {int}                [options.maxBlobSize]                     The max length in bytes allowed for the append blob to grow to.
* @param {int}                [options.appendPosition]                  The number indicating the byte offset to check for. The append will succeed only if the end position of the blob is equal to this number.
* @param {string}             [options.leaseId]                         The target blob lease identifier.
* @param {string}             [options.transactionalContentMD5]         The blob’s MD5 hash. This hash is used to verify the integrity of the blob during transport.
* @param {bool}               [options.useTransactionalMD5]             Calculate and send/validate content MD5 for transactions.
* @param {AccessConditions}   [options.accessConditions]                The access conditions.
* @param {LocationMode}       [options.locationMode]                    Specifies the location mode used to decide which location the request should be sent to. 
*                                                                       Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]             The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]        The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]        The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                       The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                       execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                 A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]               Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                       The default value is false.
* @param {errorOrResponse}    callback                                  `error` will contain information
*                                                                       if an error occurs; otherwise 
*                                                                       `response` will contain information related to this operation.
*/
BlobService.prototype._appendBlock = function (container, blob, content, stream, length, options, callback) {
  var speedSummary = options.speedSummary || new SpeedSummary(blob);
  speedSummary.totalSize = length;
 
  var self = this;
  var startAppendBlock = function () {
    var resourceName = createResourceName(container, blob);
  
    var webResource = WebResource.put(resourceName)
      .withQueryOption(QueryStringConstants.COMP, 'appendblock')
      .withHeader(HeaderConstants.CONTENT_LENGTH, length)
      .withHeader(HeaderConstants.BLOB_CONDITION_MAX_SIZE, options.maxBlobSize)
      .withHeader(HeaderConstants.BLOB_CONDITION_APPEND_POSITION, options.appendPosition);
 
    BlobResult.setHeadersFromBlob(webResource, options);
 
    var processResponseCallback = function (responseObject, next) {
      responseObject.blobResult = null;
      if (!responseObject.error) {
        responseObject.blobResult = new BlobResult(container, blob);
        responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
      }
      
      var finalCallback = function (returnObject) {
        if (!returnObject || !returnObject.error) {
          speedSummary.increment(length);
        }
        callback(returnObject.error, returnObject.blobResult, returnObject.response);
      };
      
      next(responseObject, finalCallback);
    };
 
    if (!azureutil.objectIsNull(content)) {
      self.performRequest(webResource, content, options, processResponseCallback);
    } else {
      self.performRequestOutputStream(webResource, stream, options, processResponseCallback);
    }
  };
 
  if (azureutil.objectIsNull(options.transactionalContentMD5) && options.useTransactionalMD5) {
    if (!azureutil.objectIsNull(content)) {
      options.transactionalContentMD5 = azureutil.getContentMd5(content);
      startAppendBlock();
    } else {
      azureutil.calculateMD5(stream, length, options, function (internalBuff, contentMD5) {
        options.transactionalContentMD5 = contentMD5;
        content = internalBuff;
        length = internalBuff.length;
        startAppendBlock();
      });
    }
  } else {
    startAppendBlock();
  }
  
  return options.speedSummary;
};
 
/**
* Creates and dispatches lease requests.
* @ignore
* 
* @this {BlobService}
* @param {object}             webResource                             The web resource.
* @param {string}             container                               The container name.
* @param {string}             blob                                    The blob name.
* @param {string}             leaseId                                 The lease identifier. Required to renew, change or release the lease.
* @param {string}             leaseAction                             The lease action (BlobConstants.LeaseOperation.*). Required.
* @param {object}             userOptions                             The request options.
* @param {int}                [userOptions.leaseBreakPeriod]          The lease break period.
* @param {string}             [userOptions.leaseDuration]             The lease duration. Default is never to expire.
* @param {string}             [userOptions.proposedLeaseId]           The proposed lease identifier. This is required for the CHANGE lease action.
* @param {LocationMode}       [userOptions.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                     Please see StorageUtilities.LocationMode for the possible values.
* @param {AccessConditions}   [options.accessConditions]              The access conditions.
* @param {int}                [userOptions.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]      The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [userOptions.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                     The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                     execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]               A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]             Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                     The default value is false.
* @param {Function(error, lease, response)}  callback                 `error` will contain information
*                                                                     if an error occurs; otherwise `lease` will contain
*                                                                     the lease information.
*                                                                     `response` will contain information related to this operation.
*/
BlobService.prototype._leaseImpl = function (container, blob, leaseId, leaseAction, options, callback) {
  var webResource;
  if (!azureutil.objectIsNull(blob)) {
    validate.validateArgs('_leaseImpl', function (v) {
      v.string(blob, 'blob');
    });
    var resourceName = createResourceName(container, blob);
    webResource = WebResource.put(resourceName);
  } else {
    webResource = WebResource.put(container)
      .withQueryOption(QueryStringConstants.RESTYPE, 'container');
  }
 
  webResource.withQueryOption(QueryStringConstants.COMP, 'lease')
    .withHeader(HeaderConstants.LEASE_ID, leaseId)
    .withHeader(HeaderConstants.LEASE_ACTION, leaseAction.toLowerCase())
    .withHeader(HeaderConstants.LEASE_BREAK_PERIOD, options.leaseBreakPeriod)
    .withHeader(HeaderConstants.PROPOSED_LEASE_ID, options.proposedLeaseId)
    .withHeader(HeaderConstants.LEASE_DURATION, options.leaseDuration);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.leaseResult = null;
    if (!responseObject.error) {
      responseObject.leaseResult = new LeaseResult(container, blob);
      responseObject.leaseResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.leaseResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Updates a page blob from text.
* @ignore
*
* @this {BlobService}
* @param {string}             container                                   The container name.
* @param {string}             blob                                        The blob name.
* @param {string}             text                                        The text string.
* @param {Stream}             readStream                                  The read stream.
* @param {int}                rangeStart                                  The range start.
* @param {int}                rangeEnd                                    The range end.
* @param {object}             [options]                                   The request options.
* @param {string}             [options.leaseId]                           The target blob lease identifier.
* @param {string}             [options.transactionalContentMD5]           An MD5 hash of the page content. This hash is used to verify the integrity of the page during transport. 
* @param {AccessConditions}   [options.accessConditions]                  The access conditions.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {Function(error, pageBlob, response)}  callback                  `error` will contain information
*                                                                         if an error occurs; otherwise `pageBlob` will contain
*                                                                         the blob information.
*                                                                         `response` will contain information related to this operation.
*/
BlobService.prototype._createPages = function (container, blob, text, readStream, rangeStart, rangeEnd, options, callback) {
  var request = this._updatePageBlobPagesImpl(container, blob, rangeStart, rangeEnd, BlobConstants.PageWriteOptions.UPDATE, options);
 
  // At this point, we have already validated that the range is less than 4MB. Therefore, we just need to calculate the contentMD5 if required.
  // Even when this is called from the createPagesFromStream method, it is pre-buffered and called with text.
  if (!azureutil.objectIsNull(text) && azureutil.objectIsNull(options.transactionalContentMD5) && options.useTransactionalMD5) {
    request.withHeader(HeaderConstants.CONTENT_MD5, azureutil.getContentMd5(text));
  }
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.blobResult = null;
    if (!responseObject.error) {
      responseObject.blobResult = new BlobResult(container, blob);
      responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.blobResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  if (!azureutil.objectIsNull(text)) {
    this.performRequest(request, text, options, processResponseCallback);
  } else {
    this.performRequestOutputStream(request, readStream, options, processResponseCallback);
  }
};
 
/**
* @ignore
*/
BlobService.prototype._updatePageBlobPagesImpl = function (container, blob, rangeStart, rangeEnd, writeMethod, options) {
  if (rangeStart && rangeStart % BlobConstants.PAGE_SIZE !== 0) {
    throw new RangeError(SR.INVALID_PAGE_START_OFFSET);
  }
 
  if (rangeEnd && (rangeEnd + 1) % BlobConstants.PAGE_SIZE !== 0) {
    throw new RangeError(SR.INVALID_PAGE_END_OFFSET);
  }
 
  // this is necessary if this is called from _uploadContentFromChunkStream->_createPages
  if (!options) {
    options = {};
  }
 
  options.rangeStart = rangeStart;
  options.rangeEnd = rangeEnd;
 
  options.contentLength = writeMethod === BlobConstants.PageWriteOptions.UPDATE ? (rangeEnd - rangeStart) + 1 : 0;
 
  var resourceName = createResourceName(container, blob);
  var webResource = WebResource.put(resourceName)
      .withQueryOption(QueryStringConstants.COMP, 'page')
      .withHeader(HeaderConstants.CONTENT_TYPE, 'application/octet-stream')
      .withHeader(HeaderConstants.PAGE_WRITE, writeMethod);
  
  BlobResult.setHeadersFromBlob(webResource, options);
 
  return webResource;
};
 
/**
* Uploads blob content from a stream.
* For block blob, it creates a new block to be committed.
* For page blob, it writes a range of pages.
* For append blob, it appends a new block.
*
* @ignore
*
* @this {BlobService}
* @param {string}             container                                     The container name.
* @param {string}             blob                                          The blob name.
* @param {string}             blobType                                      The blob type.
* @param (Stream)             stream                                        Stream to the data to store.
* @param {int}                streamLength                                  The length of the stream to upload.
* @param {object|function}    [options]                                     The request options.
* @param {SpeedSummary}       [options.speedSummary]                        The download tracker objects;
* @param {int}                [options.parallelOperationThreadCount]        Parallel operation thread count.
* @param {bool}               [options.absorbConditionalErrorsOnRetry]      Specifies whether to absorb the conditional error on retry. (For append blob only)
* @param {int}                [options.maxBlobSize]                         The max length in bytes allowed for the append blob to grow to.
* @param {int}                [options.appendPosition]                      The number indicating the byte offset to check for. The append will succeed only if the end position of the blob is equal to this number.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {string}             [options.blockIdPrefix]                       The prefix to be used to generate the block id. (For block blob only)
* @param {int}                [options.blockSize]                           The size of each block. Maximum is 100MB. (For block blob only)
* @param {string}             [options.leaseId]                             The lease identifier.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {bool}               [options.storeBlobContentMD5]                 Specifies whether the blob's ContentMD5 header should be set on uploads.
* @param {object}             [options.contentSettings]                     The content settings of the blob.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the blob. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the blob.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The Blob service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The blob's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The blob's MD5 hash.
* @param {AccessConditions}   [options.accessConditions]                    The access conditions.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {function(error, null)}  callback                                  The callback function.
* @return {SpeedSummary}
*/
 
BlobService.prototype._uploadContentFromChunkStream = function (container, blob, blobType, chunkStream, streamLength, options, callback) {
  this.logger.debug(util.format('_uploadContentFromChunkStream for blob %s', blob));
 
  var apiName;
  var isBlockBlobUpload;
  var isPageBlobUpload;
  var isAppendBlobUpload;
  var sizeLimitation;
  var originalContentMD5 = azureutil.tryGetValueChain(options, ['contentSettings', 'contentMD5'], null);
  var parallelOperationThreadCount = options.parallelOperationThreadCount || this.parallelOperationThreadCount;
 
  if (blobType == BlobConstants.BlobTypes.BLOCK) {
    apiName = 'createBlockFromText';
    isBlockBlobUpload = true;
 
    // BlockBlob can only have 50000 blocks in maximum
    var minBlockSize = Math.ceil(streamLength / 50000);
    if (options.blockSize) {
      if (options.blockSize < minBlockSize) {
        // options.blockSize is less than the minBlockSize, error callback        
        var error = new ArgumentError('options.blockSize', util.format('The minimum blockSize is %s and the provided blockSize %s is too small.', minBlockSize, options.blockSize));
        callback(error);
        return;
      } else {
        sizeLimitation = options.blockSize;
      }
    } else {
      // 4MB minimum for auto-calculated block size
      sizeLimitation = Math.max(minBlockSize, BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES);
    }
  } else if (blobType == BlobConstants.BlobTypes.PAGE) {
    apiName = '_createPages';
    isPageBlobUpload = true;
    sizeLimitation = BlobConstants.DEFAULT_WRITE_PAGE_SIZE_IN_BYTES;
  } else if (blobType == BlobConstants.BlobTypes.APPEND) {
    apiName = 'appendBlockFromText';
    isAppendBlobUpload = true;
    parallelOperationThreadCount = 1;
    sizeLimitation = BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES;
  } else {
    var error = new ArgumentError('blobType', util.format('Unknown blob type %s', blobType));
    callback(error);
    return;
  }
 
  chunkStream._highWaterMark = sizeLimitation;
 
  this._setOperationExpiryTime(options);
 
  // initialize the speed summary
  var speedSummary = options.speedSummary || new SpeedSummary(blob);
  speedSummary.totalSize = streamLength;
 
  // initialize chunk allocator
  var allocator = new ChunkAllocator(sizeLimitation, parallelOperationThreadCount, { logger: this.logger });
  chunkStream.setOutputLength(streamLength);
 
  // if this is a FileReadStream, set the allocator on that stream
  if (chunkStream._stream && chunkStream._stream.setMemoryAllocator) {
    chunkStream._stream.setMemoryAllocator(allocator);
  }
 
  // initialize batch operations
  var batchOperations = new BatchOperation(apiName, { callInOrder: isAppendBlobUpload, callbackInOrder: isAppendBlobUpload, logger : this.logger });
  batchOperations.setConcurrency(parallelOperationThreadCount);
 
  // initialize options
  var rangeOptions = {
    leaseId: options.leaseId,
    timeoutIntervalInMs: options.timeoutIntervalInMs,
    clientRequestTimeoutInMs: options.clientRequestTimeoutInMs,
    operationExpiryTime: options.operationExpiryTime,
    maxBlobSize: options.maxBlobSize,
    appendPosition: options.appendPosition || 0,
    initialAppendPosition: options.appendPosition || 0,
    absorbConditionalErrorsOnRetry: options.absorbConditionalErrorsOnRetry
  };
 
  // initialize block blob variables
  var blockIdPrefix = options.blockIdPrefix || this.generateBlockIdPrefix();
  var blockCount = 0;
  var blockIds = [];
  var blobResult = {};
 
  var self = this;
  chunkStream.on('data', function (data, range) {
    var operation = null;
    var full = false;
    var autoIncrement = speedSummary.getAutoIncrementFunction(data.length);
 
    if (data.length > sizeLimitation) {
      throw new RangeError(util.format(SR.EXCEEDED_SIZE_LIMITATION, sizeLimitation, data.length));
    }
 
    if (options.useTransactionalMD5) {
      //calculate content md5 for the current uploading block data
      var contentMD5 = azureutil.getContentMd5(data);
      rangeOptions.transactionalContentMD5 = contentMD5;
    }
    
    var checkLengthLimit = function () {
      if (!streamLength) return true;
      if (range.start >= streamLength) {
        self.logger.debug(util.format('Stop uploading data from %s bytes to %s bytes to blob %s because of limit %s', range.start, range.end, blob, streamLength));
        chunkStream.stop();
        return false;
      } else if (range.end >= streamLength) {
        self.logger.debug(util.format('Clip uploading data from %s bytes to %s bytes to blob %s because of limit %s', range.start, range.end, blob, streamLength));
        range.end = streamLength - 1;
        data = data.slice(0, streamLength - range.start);
        if (options.useTransactionalMD5) {
          rangeOptions.transactionalContentMD5 =  azureutil.getContentMd5(data);
        }
      }
      return true;
    };
 
    var uploadBlockBlobChunk = function () {
      if (!checkLengthLimit()) return;
      var blockId = self.getBlockId(blockIdPrefix, blockCount);
      blockIds.push(blockId);
      
      operation = new BatchOperation.RestOperation(self, apiName, blockId, container, blob, data, rangeOptions, function (error) {
        if (!error) {
          autoIncrement();
        }
        allocator.releaseBuffer(data);
        data = null;
      });
      
      blockCount++;
    };
 
    var uploadPageBlobChunk = function () {
      if (!checkLengthLimit()) return;
      
      if (azureutil.isBufferAllZero(data)) {
        self.logger.debug(util.format('Skip upload data from %s bytes to %s bytes to blob %s', range.start, range.end, blob));
        speedSummary.increment(data.length);
      } else {
        self.logger.debug(util.format('Upload data from %s bytes to %s bytes to blob %s', range.start, range.end, blob));
        operation = new BatchOperation.RestOperation(self, apiName, container, blob, data, null, range.start, range.end, rangeOptions, function (error) {
          if (!error) {
            autoIncrement();
          } else {
            self.logger.debug(util.format('Error: %s', require('util').inspect(error)));
          }
          allocator.releaseBuffer(data);
          data = null;
        });
      }
    };
 
    var uploadAppendBlobChunk = function () {
      if (!checkLengthLimit()) return;
      
      rangeOptions.appendPosition = Number(rangeOptions.initialAppendPosition) + Number(range.start);
 
      // We cannot differentiate between max size condition failing only in the retry versus failing in the first attempt and retry.  
      // So we will eliminate the latter and handle the former in the append operation callback.
      if (options.maxBlobSize && rangeOptions.appendPosition + data.length > options.maxBlobSize) {
        throw new Error(SR.MAX_BLOB_SIZE_CONDITION_NOT_MEET);
      }
 
      operation = new BatchOperation.RestOperation(self, apiName, container, blob, data, rangeOptions, function (error, currentBlob) {
        if (!error) {
          autoIncrement();
        }
        blobResult = currentBlob;
        allocator.releaseBuffer(data);
        data = null;
      });
    };
 
    if (isBlockBlobUpload) {
      uploadBlockBlobChunk();
    } else if (isAppendBlobUpload) {
      uploadAppendBlobChunk();
    } else if (isPageBlobUpload) {
      uploadPageBlobChunk();
    }
 
    if (operation) {
      full = batchOperations.addOperation(operation);
      operation = null;
 
      if (full) {
        self.logger.debug('File stream paused');
        chunkStream.pause();
      }
    }
  });
 
  chunkStream.on('end', function () {
    self.logger.debug(util.format('File read stream ended for blob %s', blob));
    batchOperations.enableComplete();
  });
 
  batchOperations.on('drain', function () {
    self.logger.debug('file stream resume');
    chunkStream.resume();
  });
 
  batchOperations.on('end', function (error) {
    self.logger.debug('batch operations commited');
 
    speedSummary = null;
    if (error) {
      callback(error);
      return;
    }
 
    if (originalContentMD5) {
      options.contentSettings.contentMD5 = originalContentMD5;
    } else if (options.storeBlobContentMD5) {
      var contentMD5 = chunkStream.getContentMd5('base64');
      azureutil.setObjectInnerPropertyValue(options, ['contentSettings', 'contentMD5'], contentMD5);
    }
 
    if (isBlockBlobUpload) {
      //commit block list
      var blockList = { 'UncommittedBlocks': blockIds };
      self.commitBlocks(container, blob, blockList, options, function (error, blockList, response) {
        self.logger.debug(util.format('Blob %s committed', blob));
 
        if (error) {
          chunkStream.finish();
 
          callback(error);
        } else {
          blobResult['commmittedBlocks'] = blockIds;
 
          chunkStream.finish();
          callback(error, blobResult, response);
        }
      });
    } else {
      // upload page blob or append blob completely
      var blobProperties = options.contentSettings;
      self.setBlobProperties(container, blob, blobProperties, function (error, blob, response) {
        chunkStream.finish();
        blob = extend(false, blob, blobResult);
        callback(error, blob, response);
      });
    }
  });
 
  return speedSummary;
};
 
/**
* Checks whether or not a container exists on the service.
* @ignore
*
* @this {BlobService}
* @param {string}             container                                         The container name.
* @param {string}             primaryOnly                                       If true, the request will be executed against the primary storage location.
* @param {object}             [options]                                         The request options.
* @param {string}             [options.leaseId]                                 The lease identifier.
* @param {LocationMode}       [options.locationMode]                            Specifies the location mode used to decide which location the request should be sent to. 
*                                                                               Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                     The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]                The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]                The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                               The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                               execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                         A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                       Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                               The default value is false.
* @param {Function(error, result, response)}  callback                          `error` will contain information
*                                                                               if an error occurs; otherwise `result` will contain
*                                                                               the container information including `exists` boolean member. 
*                                                                               `response` will contain information related to this operation.
*/
BlobService.prototype._doesContainerExist = function (container, primaryOnly, options, callback) {
  var webResource = WebResource.head(container)
    .withQueryOption(QueryStringConstants.RESTYPE, 'container')
    .withHeader(HeaderConstants.LEASE_ID, options.leaseId);
 
  if (primaryOnly === false) {
    options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY;
  }
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.containerResult = new ContainerResult(container);
    if (!responseObject.error) {
      responseObject.containerResult.exists = true;
      responseObject.containerResult.getPropertiesFromHeaders(responseObject.response.headers);
      
    } else if (responseObject.error && responseObject.error.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound) {
      responseObject.error = null;
      responseObject.containerResult.exists = false;
      responseObject.response.isSuccessful = true;
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.containerResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Checks whether or not a blob exists on the service.
* @ignore
*
* @this {BlobService}
* @param {string}             container                                         The container name.
* @param {string}             blob                                              The blob name.
* @param {string}             primaryOnly                                       If true, the request will be executed against the primary storage location.
* @param {object}             [options]                                         The request options.
* @param {string}             [options.leaseId]                                 The lease identifier.
* @param {LocationMode}       [options.locationMode]                            Specifies the location mode used to decide which location the request should be sent to. 
*                                                                               Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                     The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]                The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]                The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                               The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                               execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                         A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                       Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                               The default value is false.
* @param {Function(error, result, response)}  callback                          `error` will contain information
*                                                                               if an error occurs; otherwise `result` will contain 
*                                                                               the blob information including `exists` boolean member. 
*                                                                               `response` will contain information related to this operation.
*/
BlobService.prototype._doesBlobExist = function (container, blob, primaryOnly, options, callback) {
  var resourceName = createResourceName(container, blob);
  var webResource = WebResource.head(resourceName)
    .withHeader(HeaderConstants.LEASE_ID, options.leaseId);
 
  if (primaryOnly === false) {
    options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY;
  }
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.blobResult = new BlobResult(container, blob);
    if (!responseObject.error) {
      responseObject.blobResult.exists = true;
      responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
      
    } else if (responseObject.error && responseObject.error.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound) {
      responseObject.error = null;
      responseObject.blobResult.exists = false;
      responseObject.response.isSuccessful = true;
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.blobResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* @ignore
*/
BlobService.prototype._setBlobPropertiesHelper = function (settings) {
  var processResponseCallback = function (responseObject, next) {
    responseObject.blobResult = null;
    if (!responseObject.error) {
      responseObject.blobResult = new BlobResult(settings.container, settings.blob);
      responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
    
    var finalCallback = function (returnObject) {
      settings.callback(returnObject.error, returnObject.blobResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
  
  this.performRequest(settings.webResource, null, settings.options, processResponseCallback);
};
 
/**
* @ignore
*/
BlobService.prototype._validateLengthAndMD5 = function (options, responseObject) {
  var storedMD5 = responseObject.response.headers[Constants.HeaderConstants.CONTENT_MD5];
  var contentLength;
 
  if (!azureutil.objectIsNull(responseObject.response.headers[Constants.HeaderConstants.CONTENT_LENGTH])) {
    contentLength = parseInt(responseObject.response.headers[Constants.HeaderConstants.CONTENT_LENGTH], 10);
  }
 
  // If the user has not specified this option, the default value should be false.
  if (azureutil.objectIsNull(options.disableContentMD5Validation)) {
    options.disableContentMD5Validation = false;
  }
 
  // None of the below cases should be retried. So set the error in every case so the retry policy filter handle knows that it shouldn't be retried.
  if (options.disableContentMD5Validation === false && options.useTransactionalMD5 === true && azureutil.objectIsNull(storedMD5)) {
    responseObject.error = new StorageError(SR.MD5_NOT_PRESENT_ERROR);
    responseObject.retryable = false;
  }
 
  // Validate length and if required, MD5.
  // If getBlobToText called this method, then the responseObject.length and responseObject.contentMD5 are not set. Calculate them first using responseObject.response.body and then validate.
  if (azureutil.objectIsNull(responseObject.length)) {
    if (typeof responseObject.response.body == 'string') {
      responseObject.length = Buffer.byteLength(responseObject.response.body);
    } else if (Buffer.isBuffer(responseObject.response.body)) {
      responseObject.length = responseObject.response.body.length;
    }
  }
 
  if (!azureutil.objectIsNull(contentLength) && responseObject.length !== contentLength) {
    responseObject.error = new Error(SR.CONTENT_LENGTH_MISMATCH);
    responseObject.retryable = false;
  }
 
  if (options.disableContentMD5Validation === false && azureutil.objectIsNull(responseObject.contentMD5)) {
    responseObject.contentMD5 = azureutil.getContentMd5(responseObject.response.body);
  }
 
  if (options.disableContentMD5Validation === false && !azureutil.objectIsNull(storedMD5) && storedMD5 !== responseObject.contentMD5) {
    responseObject.error = new Error(util.format(SR.HASH_MISMATCH, storedMD5, responseObject.contentMD5));
    responseObject.retryable = false;
  }
};
 
/**
* @ignore
*/
BlobService.prototype._setRangeContentMD5Header = function (webResource, options) {
  if (!azureutil.objectIsNull(options.rangeStart) && options.useTransactionalMD5) {
    if (azureutil.objectIsNull(options.rangeEnd)) {
      throw new ArgumentNullError('options.rangeEndHeader', util.format(SR.ARGUMENT_NULL_OR_EMPTY, options.rangeEndHeader));
    }
 
    var size = parseInt(options.rangeEnd, 10) - parseInt(options.rangeStart, 10) + 1;
    if (size > BlobConstants.MAX_RANGE_GET_SIZE_WITH_MD5) {
      throw new ArgumentError('options', SR.INVALID_RANGE_FOR_MD5);
    } else {
      webResource.withHeader(HeaderConstants.RANGE_GET_CONTENT_MD5, 'true');
    }
  }
};
 
/**
* Downloads a blockblob, pageblob or appendblob into a range stream.
* @ignore
* @this {BlobService}
* @param {string}             container                                   The container name.
* @param {string}             blob                                        The blob name.
* @param {string}             blobType                                    The type of blob to download: block blob, page blob or append blob.
* @param {Stream}             writeStream                                 The write stream.
* @param {object}             [options]                                   The request options.
* @param {SpeedSummary}       [options.speedSummary]                      The download tracker objects.
* @param {int}                [options.parallelOperationThreadCount]      Parallel operation thread count.
* @param {string}             [options.snapshotId]                        The snapshot identifier.
* @param {string}             [options.leaseId]                           The lease identifier.
* @param {string}             [options.rangeStart]                        Return only the bytes of the blob in the specified range.
* @param {string}             [options.rangeEnd]                          Return only the bytes of the blob in the specified range.
* @param {AccessConditions}   [options.accessConditions]                  The access conditions.
* @param {boolean}            [options.useTransactionalMD5]               When set to true, Calculate and send/validate content MD5 for transactions.
* @param {boolean}            [options.disableContentMD5Validation]       When set to true, MD5 validation will be disabled when downloading blobs.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information if an error occurs; 
*                                                                         otherwise `result` will contain the blob information.
*                                                                         `response` will contain information related to this operation.
* @return {SpeedSummary}
*/
BlobService.prototype._getBlobToRangeStream = function (container, blob, blobType, writeStream, optionsOrCallback, callback) {
  var options;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; });
  
  validate.validateArgs('_getBlobToRangeStream', function (v) {
    v.string(container, 'container');
    v.string(blob, 'blob');
    v.containerNameIsValid(container);
    v.blobNameIsValid(container, blob);
    v.blobTypeIsValid(blobType);
    v.callback(callback);
  });
  
  var rangeStream = null;
  var isPageBlobDownload = true;
  
  if (blobType == BlobConstants.BlobTypes.PAGE) {
    rangeStream = new PageRangeStream(this, container, blob, options);
  } else if (blobType == BlobConstants.BlobTypes.APPEND) {
    rangeStream = new RangeStream(this, container, blob, options);
    isPageBlobDownload = false;
  } else if (blobType == BlobConstants.BlobTypes.BLOCK) {
    rangeStream = new BlockRangeStream(this, container, blob, options);
    isPageBlobDownload = false;
  } 
  
  if (!options.speedSummary) {
    options.speedSummary = new SpeedSummary(blob);
  }
  
  var speedSummary = options.speedSummary;
  var parallelOperationThreadCount = options.parallelOperationThreadCount || this.parallelOperationThreadCount;
  var batchOperations = new BatchOperation('getBlobInRanges', { callbackInOrder: true, logger : this.logger });
  batchOperations.setConcurrency(parallelOperationThreadCount);
 
  var self = this;
  var checkMD5sum = !options.disableContentMD5Validation;
  var md5Hash = null;
  if (checkMD5sum) {
    md5Hash = new Md5Wrapper().createMd5Hash();
  }
 
  var savedBlobResult = null;
  var savedBlobResponse = null;
 
  rangeStream.on('range', function (range) {
    if (!speedSummary.totalSize) {
      speedSummary.totalSize = rangeStream.rangeSize;
    }
 
    var requestOptions = {
      rangeStart : range.start,
      rangeEnd : range.end,
      responseEncoding : null //Use Buffer to store the response data
    };
 
    var rangeSize = range.size;
    requestOptions.timeoutIntervalInMs = options.timeoutIntervalInMs;
    requestOptions.clientRequestTimeoutInMs = options.clientRequestTimeoutInMs;
    requestOptions.useTransactionalMD5 = options.useTransactionalMD5;
 
    if (range.dataSize === 0) {
      if (isPageBlobDownload) {
        var autoIncrement = speedSummary.getAutoIncrementFunction(rangeSize);
        //No operation to do and only wait for write zero to file in callback
        var writeZeroOperation = new BatchOperation.CommonOperation(BatchOperation.noOperation, function (error) {
          if (error) return;
          var bufferAvailable = azureutil.writeZerosToStream(writeStream, rangeSize, md5Hash, autoIncrement);
          //There is no need to pause the rangestream since we can perform http request and write disk at the same time
          self.logger.debug(util.format('Write %s bytes Zero from %s to %s', rangeSize, range.start, range.end));
          if (!bufferAvailable) {
            self.logger.debug('Write stream is full and pause batch operation');
            batchOperations.pause();
          }
        });
        batchOperations.addOperation(writeZeroOperation);
      } else {
        self.logger.debug(util.format('Can not read %s bytes to %s bytes of blob %s', range.start, range.end, blob));
      }
      return;
    }
      
    if (range.start > range.end) {
      return;
    }
      
    var operation = new BatchOperation.RestOperation(self, 'getBlobToText', container, blob, requestOptions, function (error, content, blobResult, response) {
      if (!error) {
        if (rangeSize !== content.length) {
          self.logger.warn(util.format('Request %s bytes, but server returns %s bytes', rangeSize, content.length));
        }
        //Save one of the succeeded callback parameters and use them at the final callback
        if (!savedBlobResult) {
          savedBlobResult = blobResult;
        }
        if (!savedBlobResponse) {
          savedBlobResponse = response;
        }
        var autoIncrement = speedSummary.getAutoIncrementFunction(content.length);
        var bufferAvailable = writeStream.write(content, autoIncrement);
        if (!bufferAvailable) {
          self.logger.debug('Write stream is full and pause batch operation');
          batchOperations.pause();
        }
        if (md5Hash) {
          md5Hash.update(content);
        }
        content = null;
      }
    });
 
    var full = batchOperations.addOperation(operation);
    if (full) {
      self.logger.debug('Pause range stream');
      rangeStream.pause();
    }    
  });
  
  rangeStream.on('end', function () {
    self.logger.debug('Range stream has ended.');
    batchOperations.enableComplete();
  });
  
  batchOperations.on('drain', function () {
    self.logger.debug('Resume range stream');
    rangeStream.resume();
  });
  
  writeStream.on('drain', function () {
    self.logger.debug('Resume batch operations');
    batchOperations.resume();
  });
  
  batchOperations.on('end', function (error) {
    self.logger.debug('Download completed!');
    if (error) {
      callback(error);
      return;
    } else {
      writeStream.end(function () {
        self.logger.debug('Write stream has ended');
        if (writeStream.close) {
          writeStream.close();
        }
        if (!savedBlobResult) {
          savedBlobResult = {};
        }
        
        azureutil.setObjectInnerPropertyValue(savedBlobResult, ['contentSettings', 'contentMD5'], azureutil.tryGetValueChain(options, ['contentSettings', 'contentMD5'], null));
        savedBlobResult.clientSideContentMD5 = null;
        if (md5Hash) {
          savedBlobResult.clientSideContentMD5 = md5Hash.digest('base64');
        }
        callback(error, savedBlobResult, savedBlobResponse);
      });
    }
  });
  
  var listOptions = {
    timeoutIntervalInMs : options.timeoutIntervalInMs,
    clientRequestTimeoutInMs : options.clientRequestTimeoutInMs,
    snapshotId : options.snapshotId,
    leaseId : options.leaseId,
    blockListFilter : BlobUtilities.BlockListFilter.COMMITTED
  };
  
   rangeStream.list(listOptions, function (error) {
    callback(error);
  });
  
  return speedSummary;
};
 
/**
* Downloads a blockblob or pageblob into a stream.
* @ignore
* @this {BlobService}
* @param {string}             container                                   The container name.
* @param {string}             blob                                        The blob name.
* @param {Stream}             writeStream                                 The write stream.
* @param {object}             [options]                                   The request options.
* @param {string}             [options.snapshotId]                        The snapshot identifier.
* @param {string}             [options.leaseId]                           The lease identifier.
* @param {string}             [options.rangeStart]                        Return only the bytes of the blob in the specified range.
* @param {string}             [options.rangeEnd]                          Return only the bytes of the blob in the specified range.
* @param {AccessConditions}   [options.accessConditions]                  The access conditions.
* @param {boolean}            [options.useTransactionalMD5]               When set to true, Calculate and send/validate content MD5 for transactions.
* @param {boolean}            [options.disableContentMD5Validation]       When set to true, MD5 validation will be disabled when downloading blobs.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information if an error occurs; 
*                                                                         otherwise `result` will contain the blob information.
*                                                                         `response` will contain information related to this operation.
*/
BlobService.prototype._getBlobToStream = function (container, blob, writeStream, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  
  var resourceName = createResourceName(container, blob);
  var webResource = WebResource.get(resourceName).withRawResponse();
  
  var options = extend(true, {}, userOptions);
  webResource.withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId);
  
  BlobResult.setHeadersFromBlob(webResource, options);
  
  this._setRangeContentMD5Header(webResource, options);
  
  var self = this;
  var processResponseCallback = function (responseObject, next) {
    responseObject.blobResult = null;
    
    if (!responseObject.error) {
      responseObject.blobResult = new BlobResult(container, blob);
      responseObject.blobResult.metadata = self.parseMetadataHeaders(responseObject.response.headers);
      responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers);
      
      self._validateLengthAndMD5(options, responseObject);
    }
    
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.blobResult, returnObject.response);
    };
    
    next(responseObject, finalCallback);
  };
  
  this.performRequestInputStream(webResource, null, writeStream, options, processResponseCallback);
};
 
/**
* Downloads a blob into a file.
* @ignore
* @this {BlobService}
* @param {string}             container                                   The container name.
* @param {string}             blob                                        The blob name.
* @param {string}             localFileName                               The local path to the file to be downloaded.
* @param {object}             [options]                                   The request options.
* @param {boolean}            [options.skipSizeCheck]                     Skip the size check to perform direct download.
*                                                                         Set the option to true for small blobs.
*                                                                         Parallel download and speed summary won't work with this option on.
* @param {SpeedSummary}       [options.speedSummary]                      The download tracker objects.
* @param {int}                [options.parallelOperationThreadCount]      Parallel operation thread count.
* @param {string}             [options.snapshotId]                        The snapshot identifier.
* @param {string}             [options.leaseId]                           The lease identifier.
* @param {string}             [options.rangeStart]                        Return only the bytes of the blob in the specified range.
* @param {string}             [options.rangeEnd]                          Return only the bytes of the blob in the specified range.
* @param {AccessConditions}   [options.accessConditions]                  The access conditions.
* @param {boolean}            [options.useTransactionalMD5]               When set to true, Calculate and send/validate content MD5 for transactions.
* @param {boolean}            [options.disableContentMD5Validation]       When set to true, MD5 validation will be disabled when downloading blobs.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information if an error occurs; 
*                                                                         otherwise `result` will contain the blob information.
*                                                                         `response` will contain information related to this operation.
* @return {SpeedSummary}
* 
*/
BlobService.prototype._getBlobToLocalFile = function (container, blob, localFileName, optionsOrCallback, callback) {
  var options;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; });
  options.speedSummary = options.speedSummary || new SpeedSummary(blob);
  
  var writeStream = fs.createWriteStream(localFileName, { 'highWaterMark': BlobConstants.MAX_QUEUED_WRITE_DISK_BUFFER_SIZE });
  
  this.getBlobToStream(container, blob, writeStream, options, function (error, responseBlob, response) {
    if (error) {
      if (azureutil.pathExistsSync(localFileName)) {
        // make sure writeStream is closed / destroyed to avoid locking issues
        if (writeStream.close) {
          writeStream.close();
        }
        
        // If the download failed from the beginning, remove the file.
        fs.unlink(localFileName, function () {
          callback(error, responseBlob, response);
        });
        return;
      }
    }
    callback(error, responseBlob, response);
  });
  
  return options.speedSummary;
};
 
/**
* Lists a segment containing a collection of blob items whose names begin with the specified prefix in the container.
* @ignore
* @this {BlobService}
* @param {string}             container                           The container name.
* @param {string}             prefix                              The prefix of the blob name.
* @param {object}             currentToken                        A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {ListBlobTypes}      listBlobType                        Specifies the item type of the results.
* @param {object}             [options]                           The request options.
* @param {int}                [options.maxResults]                Specifies the maximum number of blobs to return per call to Azure ServiceClient. This does NOT affect list size returned by this function. (maximum: 5000)
* @param {string}             [options.include]                   Specifies that the response should include one or more of the following subsets: '', 'metadata', 'snapshots', 'uncommittedblobs', 'copy').
*                                                                 Please find these values in BlobUtilities.BlobListingDetails. Multiple values can be added separated with a comma (,).
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise `result` will contain
*                                                                 the entries of blobs and the continuation token for the next listing operation.
*                                                                 `response` will contain information related to this operation.
*/
BlobService.prototype._listBlobsOrDircotriesSegmentedWithPrefix = function (container, prefix, currentToken, listBlobType, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  
  validate.validateArgs('listBlobsSegmented', function (v) {
    v.string(container, 'container');
    v.containerNameIsValid(container);
    v.callback(callback);
  });
  
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.get(container)
    .withQueryOption(QueryStringConstants.RESTYPE, 'container')
    .withQueryOption(QueryStringConstants.COMP, 'list')
    .withQueryOption(QueryStringConstants.MAX_RESULTS, options.maxResults)
    .withQueryOptions(options,
      QueryStringConstants.DELIMITER,
      QueryStringConstants.INCLUDE);
  
  if (!azureutil.objectIsNull(currentToken)) {
    webResource.withQueryOption(QueryStringConstants.MARKER, currentToken.nextMarker);
  }
  
  webResource.withQueryOption(QueryStringConstants.PREFIX, prefix);
  
  options.requestLocationMode = azureutil.getNextListingLocationMode(currentToken);
  
  var processResponseCallback = function (responseObject, next) {
    responseObject.listBlobsResult = null;
    if (!responseObject.error) {
      responseObject.listBlobsResult = {
        entries: null,
        continuationToken: null
      };
      
      responseObject.listBlobsResult.entries = [];
      var results = [];
      
      if (listBlobType == BlobConstants.ListBlobTypes.Directory && responseObject.response.body.EnumerationResults.Blobs.BlobPrefix) {
        results = responseObject.response.body.EnumerationResults.Blobs.BlobPrefix;
        if (!_.isArray(results)) {
          results = [results];
        }
      } else if (listBlobType == BlobConstants.ListBlobTypes.Blob && responseObject.response.body.EnumerationResults.Blobs.Blob) {
        results = responseObject.response.body.EnumerationResults.Blobs.Blob;
        if (!_.isArray(results)) {
          results = [results];
        }
      }
      
      results.forEach(function (currentBlob) {
        var blobResult = BlobResult.parse(currentBlob);
        responseObject.listBlobsResult.entries.push(blobResult);
      });
      
      if (responseObject.response.body.EnumerationResults.NextMarker) {
        responseObject.listBlobsResult.continuationToken = {
          nextMarker: null,
          targetLocation: null
        };
        
        responseObject.listBlobsResult.continuationToken.nextMarker = responseObject.response.body.EnumerationResults.NextMarker;
        responseObject.listBlobsResult.continuationToken.targetLocation = responseObject.targetLocation;
      }
    }
    
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.listBlobsResult, returnObject.response);
    };
    
    next(responseObject, finalCallback);
  };
  
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Create a new blob.
* @ignore
* 
* @this {BlobService}
* @param {string}             container                                The container name.
* @param {string}             blob                                     The blob name.
* @param (BlobType)           blobType                                 The blob type.
* @param {int}                size                                     The blob size. 
* @param {object}             [options]                                The request options.
* @param {errorOrResult}      callback                                 The callback which operates on the specific blob.
*/
BlobService.prototype._createBlob = function (container, blob, blobType, size, options, creationCallback) {
  if (blobType == BlobConstants.BlobTypes.APPEND) {
    this.createOrReplaceAppendBlob(container, blob, options, function (createError, createResponse) {
      creationCallback(createError, null, createResponse);
    });
  } else if (blobType == BlobConstants.BlobTypes.PAGE) {
    this.createPageBlob(container, blob, size, options, function (createError) {
      creationCallback(createError);
    });
  } else if (blobType == BlobConstants.BlobTypes.BLOCK) {
    creationCallback();
  }
};
 
/**
* The callback for {BlobService~getBlobToText}.
* @typedef {function} BlobService~blobToText
* @param {object} error      If an error occurs, the error information.
* @param {string} text       The text returned from the blob.
* @param {object} blockBlob  Information about the blob.
* @param {object} response   Information related to this operation.
*/
 
BlobService.SpeedSummary = SpeedSummary;
 
module.exports = BlobService;
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/blobutilities.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/blobutilities.js

Statements: 100% (3 / 3)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (3 / 3)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101                                  1           1                                                                                                                                                       1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Expose 'BlobUtilities'.
exports = module.exports;
 
/**
* Defines constants, enums, and utility functions for use with the Blob service.
* @namespace BlobUtilities
*/
var BlobUtilities = {
  /**
  * Permission types
  *
  * @const
  * @enum {string}
  */
  SharedAccessPermissions: {
    READ: 'r',
    ADD: 'a',
    CREATE: 'c',
    WRITE: 'w',
    DELETE: 'd',
    LIST: 'l'
  },
 
  /**
  * Blob listing details.
  *
  * @const
  * @enum {string}
  */
  BlobListingDetails: {
    SNAPSHOTS: 'snapshots',
    METADATA: 'metadata',
    UNCOMMITTED_BLOBS: 'uncommittedblobs',
    COPY: 'copy'
  },
 
  /**
  * Deletion options for blob snapshots
  *
  * @const
  * @enum {string}
  */
  SnapshotDeleteOptions: {
    SNAPSHOTS_ONLY: 'only',
    BLOB_AND_SNAPSHOTS: 'include'
  },
 
  /**
  * Type of block list to retrieve
  *
  * @const
  * @enum {string}
  */
  BlockListFilter: {
    ALL: 'all',
    COMMITTED: 'committed',
    UNCOMMITTED: 'uncommitted'
  },
 
  /**
  * Blobs and container public access types.
  *
  * @const
  * @enum {string}
  */
  BlobContainerPublicAccessType: {
    OFF: null,
    CONTAINER: 'container',
    BLOB: 'blob'
  },
 
  /**
  * Describes actions that can be performed on a page blob sequence number.
  * @const
  * @enum
  */
  SequenceNumberAction: {
    MAX: 'max',
    UPDATE: 'update',
    INCREMENT: 'increment'
  }
};
 
module.exports = BlobUtilities;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/internal/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/internal/

Statements: 15.65% (18 / 115)      Branches: 0% (0 / 49)      Functions: 0% (0 / 11)      Lines: 15.79% (18 / 114)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/internal/
File Statements Branches Functions Lines
blockrangestream.js 12% (12 / 100) 0% (0 / 45) 0% (0 / 10) 12.12% (12 / 99)
pagerangestream.js 40% (6 / 15) 0% (0 / 4) 0% (0 / 1) 40% (6 / 15)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/internal/blockrangestream.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/internal/blockrangestream.js

Statements: 12% (12 / 100)      Branches: 0% (0 / 45)      Functions: 0% (0 / 10)      Lines: 12.12% (12 / 99)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196                                1 1 1         1                                                     1             1                                                             1                           1                                                           1                                                                                             1             1             1    
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var Constants = require('./../../../common/util/constants');
var EventEmitter = require('events').EventEmitter;
var BlobUtilities = require('./../blobutilities');
 
/**
* BlockBlob block range stream
*/
function BlockRangeStream(blobServiceClient, container, blob, options) {
  this.blobServiceClient = blobServiceClient;
  this.container = container;
  this.blob = blob;
  this._emitter = new EventEmitter();
  this._paused = false;
  this._emittedAll = false;
  this._emittedRangeType = null;
  this._emittedRangeIndex = null;
  this._offset = 0;
  this._rangelist = [];
  this._isEmitting = false;
  if (options.rangeStart) {
    this._startOffset = options.rangeStart;
  } else {
    this._startOffset = 0;
  }
  if (options.rangeEnd) {
    this._endOffset = options.rangeEnd;
  } else {
    this._endOffset = Number.MAX_VALUE;
  }
}
 
/**
* Add event listener
*/
BlockRangeStream.prototype.on = function (event, listener) {
  this._emitter.on(event, listener);
};
 
/**
* Get block list
*/
BlockRangeStream.prototype.list = function (options, callback) {
  if (!options) {
    options = {};
  }
  
  if (!options.blockListFilter) {
    options.blockListFilter = BlobUtilities.BlockListFilter.ALL;
  }
  
  var self = this;
  this.blobServiceClient.listBlocks(this.container, this.blob, options.blockListFilter, options, function (error, blocklist, response) {
    if (error) {
      callback(error);
    } else {
      var totalSize = parseInt(response.headers[Constants.HeaderConstants.BLOB_CONTENT_LENGTH], 10);
      if (!blocklist.CommittedBlocks) {
        //Convert single block blob to block blob range
        var name = 'NODESDK_BLOCKBLOB_RANGESTREAM';
        blocklist.CommittedBlocks = [{ Name : name, Size : totalSize }];
      }
      
      self._rangelist = blocklist;
      self._emitBlockList();
      self = blocklist = null;
    }
  });
};
 
/**
* Emit block ranges
*/
BlockRangeStream.prototype._emitBlockList = function () {
  if (this._paused || this._emittedAll || this._isEmitting) return;
  
  var self = this;
  this._getTypeList(function () {
    self._rangelist = null;
    self._emittedAll = true;
    self._emitter.emit('end');
  });
};
 
/**
* Get the block type list
*/
BlockRangeStream.prototype._getTypeList = function (callback) {
  this._isEmitting = true;
  try {
    var typeStart = false;
    if (this._rangelist) {
      for (var blockType in this._rangelist) {
        if (this._rangelist.hasOwnProperty(blockType)) {
          if (this._emittedRangeType === null || typeStart || this._emittedRangeType == blockType) {
            this._emittedRangeType = blockType;
            typeStart = true;
          } else if (this._emittedRangeType !== blockType) {
            continue;
          }
          
          if (this._paused) {
            return;
          }
          
          this._emitBlockRange (blockType, callback);
        }
      }
    }
  } finally {
    this._isEmitting = false;
  }
};
 
/**
* Get the block list
*/
BlockRangeStream.prototype._emitBlockRange  = function (blockType, callback) {
  var blockList = this._rangelist[blockType];
  var indexStart = false;
  for (var blockIndex = 0; blockIndex < blockList.length; blockIndex++) {
    if (this._emittedRangeIndex === null || indexStart || this._emittedRangeIndex === blockIndex) {
      this._emittedRangeIndex = blockIndex;
      indexStart = true;
    } else if (this._emittedRangeIndex !== blockIndex) {
      continue;
    }
    
    if (this._paused) {
      return;
    }
    
    var range = blockList[blockIndex];
    // follow the same naming convention of page ranges and json
    range.name = range.Name;
    range.type = blockType;
    range.start = this._offset;
    this._offset += parseInt(range.Size, 10);
    range.end = this._offset - 1;
    delete range.Name;
    delete range.Size;
    
    if (range.start > this._endOffset) {
      break;
    } else if (range.end < this._startOffset) {
      continue;
    } else {
      range.start = Math.max(range.start, this._startOffset);
      range.end = Math.min(range.end, this._endOffset);
      range.size = range.end - range.start + 1;
      range.dataSize = range.size;
      this._emitter.emit('range', range);
    }
  }
 
  // remove the used range and avoid memory leak
  this._rangelist[blockType] = null;
 
  callback();
};
 
/**
* Pause the stream
*/
BlockRangeStream.prototype.pause = function () {
  this._paused = true;
};
 
/**
* Resume the stream
*/
BlockRangeStream.prototype.resume = function () {
  this._paused = false;
  if (!this._isEmitting) {
    this._emitBlockList();
  }
};
 
module.exports = BlockRangeStream;
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/internal/pagerangestream.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/internal/pagerangestream.js

Statements: 40% (6 / 15)      Branches: 0% (0 / 4)      Functions: 0% (0 / 1)      Lines: 40% (6 / 15)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45                                1 1 1         1                                 1   1    
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var util = require('util');
var RangeStream = require('./../../../common/streams/rangestream');
var Constants = require('./../../../common/util/constants');
 
/**
* PageBlob page range stream
*/
function PageRangeStream(blobServiceClient, container, blob, options) {
  PageRangeStream['super_'].call(this, blobServiceClient, container, blob, options);
  
  if (options.minRangeSize) {
    this._minRangeSize = options.minRangeSize;
  } else {
    this._minRangeSize = Constants.BlobConstants.MIN_WRITE_PAGE_SIZE_IN_BYTES;
  }
  if (options.maxRangeSize) {
    this._maxRangeSize = options.maxRangeSize;
  } else {
    this._maxRangeSize = Constants.BlobConstants.DEFAULT_WRITE_PAGE_SIZE_IN_BYTES;
  }
  this._lengthHeader = Constants.HeaderConstants.BLOB_CONTENT_LENGTH;
  this._listFunc = blobServiceClient.listPageRanges;
}
 
util.inherits(PageRangeStream, RangeStream);
 
module.exports = PageRangeStream;
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/models/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/models/

Statements: 18.18% (32 / 176)      Branches: 0% (0 / 92)      Functions: 0% (0 / 22)      Lines: 18.18% (32 / 176)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/models/
File Statements Branches Functions Lines
blobresult.js 14.63% (12 / 82) 0% (0 / 36) 0% (0 / 9) 14.63% (12 / 82)
blocklistresult.js 18.75% (6 / 32) 0% (0 / 18) 0% (0 / 7) 18.75% (6 / 32)
containerresult.js 21.43% (9 / 42) 0% (0 / 22) 0% (0 / 4) 21.43% (9 / 42)
leaseresult.js 25% (5 / 20) 0% (0 / 16) 0% (0 / 2) 25% (5 / 20)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/models/blobresult.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/models/blobresult.js

Statements: 14.63% (12 / 82)      Branches: 0% (0 / 36)      Functions: 0% (0 / 9)      Lines: 14.63% (12 / 82)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284                                  1   1 1 1 1                                                                                         1                   1                                                   1                                                                                       1                                                                   1                                                                                                                               1                                                                       1    
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var _ = require('underscore');
 
var azureCommon = require('./../../../common/common');
var azureutil = azureCommon.util;
var Constants = azureCommon.Constants;
var HeaderConstants = Constants.HeaderConstants;
 
/**
* Creates a new BlobResult object.
* @class
* The BlobResult class is used to store the blob information.
* 
 * @property  {string}                      container                             The container name.
 * @property  {string}                      name                                  The blob name.
 * @property  {object}                      metadata                              The metadata key/value pair.
 * @property  {string}                      etag                                  The etag.
 * @property  {string}                      lastModified                          The date/time that the blob was last modified.
 * @property  {string}                      contentLength                         The size of the blob in bytes.
 * @property  {string}                      blobType                              The blob type.
 * @property  {boolean}                     isIncrementalCopy                     If the blob is incremental copy blob.
 * @property  {string}                      requestId                             The request id.
 * @property  {string}                      sequenceNumber                        The current sequence number for a page blob.
 * @property  {string}                      contentRange                          The content range.
 * @property  {string}                      committedBlockCount                   The committed block count.
 * @property  {string}                      serverEncrypted                       If the blob data and application metadata are completely encrypted using the specified algorithm. true/false.
 * @property  {object}                      contentSettings                       The content settings.
 * @property  {string}                      contentSettings.contentType           The content type.
 * @property  {string}                      contentSettings.contentEncoding       The content encoding.
 * @property  {string}                      contentSettings.contentLanguage       The content language.
 * @property  {string}                      contentSettings.cacheControl          The cache control.
 * @property  {string}                      contentSettings.contentDisposition    The content disposition.
 * @property  {string}                      contentSettings.contentMD5            The content MD5 hash.
 * @property  {object}                      lease                                 The lease information.
 * @property  {string}                      lease.id                              The lease id.
 * @property  {string}                      lease.status                          The lease status.
 * @property  {string}                      lease.state                           The lease state.
 * @property  {string}                      lease.duration                        The lease duration.
 * @property  {object}                      copy                                  The copy information.
 * @property  {string}                      copy.id                               The copy id.
 * @property  {string}                      copy.status                           The copy status.
 * @property  {string}                      copy.completionTime                   The copy completion time. 
 * @property  {string}                      copy.statusDescription                The copy status description.
 * @property  {string}                      copy.destinationSnapshot              The snapshot time of the last successful incremental copy snapshot for this blob.
 * @property  {string}                      copy.progress                         The copy progress.
 * @property  {string}                      copy.source                           The copy source.
 * 
* @constructor
* @param {string} [container]  The container name.
* @param {string} [name]       The blob name.
*/
function BlobResult(container, name) {
  if (container) {
    this.container = container;
  }
 
  if (name) {
    this.name = name;
  }
}
 
BlobResult.parse = function (blobXml) {
  var blobResult = new BlobResult();
  
  for (var propertyName in blobXml) {
    if (blobXml.hasOwnProperty(propertyName)) {
      if (propertyName === 'Properties') {
        //  Lift out the properties onto the main object to keep consistent across all APIs like: getBlobProperties
        azureutil.setPropertyValueFromXML(blobResult, blobXml[propertyName], true);
      } else if (propertyName === 'Metadata') {
        var resultPropertyName = azureutil.normalizePropertyNameFromXML(propertyName);
        blobResult[resultPropertyName] = {};
        azureutil.setPropertyValueFromXML(blobResult[resultPropertyName], blobXml[propertyName], false);
      } else {
        blobResult[propertyName.toLowerCase()] = blobXml[propertyName];
      }
    }
  }
 
  // convert isIncrementalCopy to boolean type
  if (blobResult.isIncrementalCopy !== undefined) {
    blobResult.isIncrementalCopy = (blobResult.isIncrementalCopy == 'true');
  }
 
  return blobResult;
};
 
var headersForProperties = {
  'lastModified': 'LAST_MODIFIED',
  'etag': 'ETAG',
  'sequenceNumber': 'SEQUENCE_NUMBER',
  'blobType': 'BLOB_TYPE',
  'contentLength': 'CONTENT_LENGTH',
  'blobContentLength': 'BLOB_CONTENT_LENGTH',
  'contentRange': 'CONTENT_RANGE',
  'committedBlockCount': 'BLOB_COMMITTED_BLOCK_COUNT',
  'serverEncrypted': 'SERVER_ENCRYPTED',
  'requestId': 'REQUEST_ID',
  
  'range': 'RANGE',
  'blobRange': 'STORAGE_RANGE',
  'getContentMd5': 'RANGE_GET_CONTENT_MD5',
  'acceptRanges': 'ACCEPT_RANGES',
  'appendOffset': 'BLOB_APPEND_OFFSET',
 
  'isIncrementalCopy': 'INCREMENTAL_COPY',
  
  // ContentSettings
  'contentSettings.contentType': 'CONTENT_TYPE',
  'contentSettings.contentEncoding': 'CONTENT_ENCODING',
  'contentSettings.contentLanguage': 'CONTENT_LANGUAGE',
  'contentSettings.cacheControl': 'CACHE_CONTROL',
  'contentSettings.contentDisposition': 'CONTENT_DISPOSITION',
  'contentSettings.contentMD5': 'CONTENT_MD5',
 
  // Lease
  'lease.id': 'LEASE_ID',
  'lease.status': 'LEASE_STATUS',
  'lease.duration': 'LEASE_DURATION',
  'lease.state': 'LEASE_STATE',
 
  // Copy
  'copy.id': 'COPY_ID',
  'copy.status': 'COPY_STATUS',
  'copy.source': 'COPY_SOURCE',
  'copy.progress': 'COPY_PROGRESS',
  'copy.completionTime': 'COPY_COMPLETION_TIME',
  'copy.statusDescription': 'COPY_STATUS_DESCRIPTION',
  'copy.destinationSnapshot': 'COPY_DESTINATION_SNAPSHOT'
};
 
BlobResult.prototype.getPropertiesFromHeaders = function (headers) {
  var self = this;
 
  var setBlobPropertyFromHeaders = function (blobProperty, headerProperty) {
    if (!azureutil.tryGetValueChain(self, blobProperty.split('.'), null) && headers[headerProperty.toLowerCase()]) {
      azureutil.setObjectInnerPropertyValue(self, blobProperty.split('.'), headers[headerProperty.toLowerCase()]);
      
      if (blobProperty === 'copy.progress') {
        var info = azureutil.parseCopyProgress(self.copy.progress);
        self.copy.bytesCopied = parseInt(info.bytesCopied);
        self.copy.totalBytes = parseInt(info.totalBytes);
      }
    }
  };
 
  // For range get, 'x-ms-blob-content-md5' indicate the overall MD5 of the blob. Try to set the contentMD5 using this header if it presents
  setBlobPropertyFromHeaders('contentSettings.contentMD5', HeaderConstants['BLOB_CONTENT_MD5']);
  
  _.chain(headersForProperties).pairs().each(function (pair) {
    var property = pair[0];
    var header = HeaderConstants[pair[1]];
    setBlobPropertyFromHeaders(property, header);
  });
 
  // convert isIncrementalCopy to boolean type
  if (self.isIncrementalCopy !== undefined) {
    self.isIncrementalCopy = (self.isIncrementalCopy == 'true');
  }
};
 
/**
* This method sets the HTTP headers and is used by all methods except setBlobProperties and commitBlocks. Those 2 methods will set the x-ms-* headers using setPropertiesFromBlob.
* @ignore
*/
BlobResult.setHeadersFromBlob = function (webResource, blob) {
  var setHeaderPropertyFromBlob = function (headerProperty, blobProperty) {
    var blobPropertyValue = azureutil.tryGetValueChain(blob, blobProperty.split('.'), null);
    if (blobPropertyValue) {
      webResource.withHeader(headerProperty, blobPropertyValue);
    }
  };
 
  if (blob) {
    // Content-Type
    setHeaderPropertyFromBlob(HeaderConstants.BLOB_CONTENT_TYPE, 'contentSettings.contentType');
 
    // Content-Encoding
    setHeaderPropertyFromBlob(HeaderConstants.BLOB_CONTENT_ENCODING, 'contentSettings.contentEncoding');
 
    // Content-Language
    setHeaderPropertyFromBlob(HeaderConstants.BLOB_CONTENT_LANGUAGE, 'contentSettings.contentLanguage');
 
    // Content-Disposition
    setHeaderPropertyFromBlob(HeaderConstants.BLOB_CONTENT_DISPOSITION, 'contentSettings.contentDisposition');
 
    // Cache-Control
    setHeaderPropertyFromBlob(HeaderConstants.BLOB_CACHE_CONTROL, 'contentSettings.cacheControl');
 
    // Blob's Content-MD5
    setHeaderPropertyFromBlob(HeaderConstants.BLOB_CONTENT_MD5, 'contentSettings.contentMD5');
 
    // Content-Length
    setHeaderPropertyFromBlob(HeaderConstants.CONTENT_LENGTH, 'contentLength');
 
    // transactional Content-MD5
    setHeaderPropertyFromBlob(HeaderConstants.CONTENT_MD5, 'transactionalContentMD5');
 
    // Range
    if (!azureutil.objectIsNull(blob.rangeStart)) {
      var range = 'bytes=' + blob.rangeStart + '-';
 
      if (!azureutil.objectIsNull(blob.rangeEnd)) {
        range += blob.rangeEnd;
      }
 
      webResource.withHeader(HeaderConstants.RANGE, range);
    }
 
    // Blob Type
    setHeaderPropertyFromBlob(HeaderConstants.BLOB_TYPE, 'blobType');
 
    // Lease id
    setHeaderPropertyFromBlob(HeaderConstants.LEASE_ID, 'leaseId');
 
    // Sequence number
    setHeaderPropertyFromBlob(HeaderConstants.SEQUENCE_NUMBER, 'sequenceNumber');
    setHeaderPropertyFromBlob(HeaderConstants.SEQUENCE_NUMBER_ACTION, 'sequenceNumberAction');
 
    if (blob.metadata) {
      webResource.addOptionalMetadataHeaders(blob.metadata);
    }
  }
};
 
/**
* This method sets the x-ms-* headers and is used by setBlobProperties and commitBlocks. All other methods will set the regular HTTP headers using setHeadersFromBlob.
* @ignore
*/
BlobResult.setPropertiesFromBlob = function (webResource, blob) {
  var setHeaderPropertyFromBlob = function (headerProperty, blobProperty) {
    var propertyValue = azureutil.tryGetValueChain(blob, blobProperty.split('.'), null);
    if (propertyValue) {
      webResource.withHeader(headerProperty, propertyValue);
    }
  };
 
  if (blob) {
    // Content-Type
    setHeaderPropertyFromBlob(HeaderConstants.BLOB_CONTENT_TYPE, 'contentSettings.contentType');
 
    // Content-Encoding
    setHeaderPropertyFromBlob(HeaderConstants.BLOB_CONTENT_ENCODING, 'contentSettings.contentEncoding');
 
    // Content-Language
    setHeaderPropertyFromBlob(HeaderConstants.BLOB_CONTENT_LANGUAGE, 'contentSettings.contentLanguage');
 
    // Content-Disposition
    setHeaderPropertyFromBlob(HeaderConstants.BLOB_CONTENT_DISPOSITION, 'contentSettings.contentDisposition');
 
    // Cache-Control
    setHeaderPropertyFromBlob(HeaderConstants.BLOB_CACHE_CONTROL, 'contentSettings.cacheControl');
 
    // Content-MD5
    setHeaderPropertyFromBlob(HeaderConstants.BLOB_CONTENT_MD5, 'contentSettings.contentMD5');
 
    // Lease id
    setHeaderPropertyFromBlob(HeaderConstants.LEASE_ID, 'leaseId');
 
    if (blob.metadata) {
      webResource.addOptionalMetadataHeaders(blob.metadata);
    }
  }
};
 
module.exports = BlobResult;
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/models/blocklistresult.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/models/blocklistresult.js

Statements: 18.75% (6 / 32)      Branches: 0% (0 / 18)      Functions: 0% (0 / 7)      Lines: 18.75% (6 / 32)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86                                  1   1 1 1               1                                                             1                                                  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var _ = require('underscore');
 
var azureCommon = require('./../../../common/common');
var xmlbuilder = azureCommon.xmlbuilder;
var Constants = azureCommon.Constants;
 
/**
* Builds an XML representation for a block list.
*
* @param  {array}  The block list.
* @return {string} The XML block list.
*/
exports.serialize = function (blockListJs) {
  var blockListDoc = xmlbuilder.create();
  blockListDoc = blockListDoc.begin(Constants.BlobConstants.BLOCK_LIST_ELEMENT, { version: '1.0', encoding: 'utf-8' });
 
  if (blockListJs.LatestBlocks) {
    blockListJs.LatestBlocks.forEach(function (block) {
      blockListDoc = blockListDoc.ele(Constants.BlobConstants.LATEST_ELEMENT)
        .txt(new Buffer(block).toString('base64'))
        .up();
    });
  }
 
  if (blockListJs.CommittedBlocks) {
    blockListJs.CommittedBlocks.forEach(function (block) {
      blockListDoc = blockListDoc.ele(Constants.BlobConstants.COMMITTED_ELEMENT)
        .txt(new Buffer(block).toString('base64'))
        .up();
    });
  }
 
  if (blockListJs.UncommittedBlocks) {
    blockListJs.UncommittedBlocks.forEach(function (block) {
      blockListDoc = blockListDoc.ele(Constants.BlobConstants.UNCOMMITTED_ELEMENT)
        .txt(new Buffer(block).toString('base64'))
        .up();
    });
  }
 
  return blockListDoc.doc().toString();
};
 
exports.parse = function (blockListXml) {
  var blockListResult = {};
 
  if (blockListXml.CommittedBlocks && blockListXml.CommittedBlocks.Block) {
    blockListResult.CommittedBlocks = blockListXml.CommittedBlocks.Block;
    if (!_.isArray(blockListResult.CommittedBlocks)) {
      blockListResult.CommittedBlocks = [blockListResult.CommittedBlocks];
    }
    blockListResult.CommittedBlocks.forEach(function(block) {
      block.Name = new Buffer(block.Name, 'base64').toString();
    });
  }
 
  if (blockListXml.UncommittedBlocks && blockListXml.UncommittedBlocks.Block) {
    blockListResult.UncommittedBlocks = blockListXml.UncommittedBlocks.Block;
    if (!_.isArray(blockListResult.UncommittedBlocks)) {
      blockListResult.UncommittedBlocks = [blockListResult.UncommittedBlocks];
    }
    blockListResult.UncommittedBlocks.forEach(function(block) {
      block.Name = new Buffer(block.Name, 'base64').toString();
    });
  }
 
  return blockListResult;
};
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/models/containerresult.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/models/containerresult.js

Statements: 21.43% (9 / 42)      Branches: 0% (0 / 22)      Functions: 0% (0 / 4)      Lines: 21.43% (9 / 42)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117                                  1 1 1   1 1                                           1                   1                                                 1                                                                       1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var azureCommon = require('./../../../common/common');
var azureutil = azureCommon.util;
var Constants = azureCommon.Constants;
 
var HeaderConstants = Constants.HeaderConstants;
var BlobUtilities = require('../blobutilities');
 
/**
* Creates a new ContainerResult object.
* @class
* The ContainerResult class is used to store the container information.
* 
 * @property  {string}                      name                                  The container name.
 * @property  {string}                      publicAccessLevel                     The public access level.
 * @property  {object}                      metadata                              The metadata key/value pair.
 * @property  {string}                      etag                                  The etag.
 * @property  {string}                      lastModified                          The date/time that the container was last modified.
 * @property  {string}                      requestId                             The request id.
 * @property  {object}                      lease                                 The lease information.
 * @property  {string}                      lease.status                          The lease status.
 * @property  {string}                      lease.state                           The lease state.
 * @property  {string}                      lease.duration                        The lease duration.
 * 
* @constructor
* @param {string} [container]               The container name.
* @param {string} [publicAccessLevel]       The public access level.
*/
function ContainerResult(name, publicAccessLevel) {
  if (name) {
    this.name = name;
  }
 
  if (publicAccessLevel) {
    this.publicAccessLevel = publicAccessLevel;
  }
}
 
ContainerResult.parse = function (containerXml) {
  var containerResult = new ContainerResult();
  
  for (var propertyName in containerXml) {
    if (containerXml.hasOwnProperty(propertyName)) {
      if (propertyName === 'Properties') {
        //  Lift out the properties onto the main object to keep consistent across all APIs like: getContainerProperties
        azureutil.setPropertyValueFromXML(containerResult, containerXml[propertyName], true);
      } else if (propertyName === 'Metadata') {
        var resultPropertyName = azureutil.normalizePropertyNameFromXML(propertyName);
        containerResult[resultPropertyName] = {};
        azureutil.setPropertyValueFromXML(containerResult[resultPropertyName], containerXml[propertyName], false);
      } else {
        containerResult[propertyName.toLowerCase()] = containerXml[propertyName];
      }
    }
  }
 
  if (!containerResult.publicAccessLevel) {
    containerResult.publicAccessLevel = BlobUtilities.BlobContainerPublicAccessType.OFF;
  }
 
  return containerResult;
};
 
ContainerResult.prototype.getPropertiesFromHeaders = function (headers) {
  var self = this;
  
  var setContainerPropertyFromHeaders = function (containerProperty, headerProperty) {
    if (!azureutil.tryGetValueChain(self, containerProperty.split('.'), null) && headers[headerProperty.toLowerCase()]) {
      azureutil.setObjectInnerPropertyValue(self, containerProperty.split('.'), headers[headerProperty.toLowerCase()]);
    }
  };
 
  setContainerPropertyFromHeaders('etag', HeaderConstants.ETAG);
  setContainerPropertyFromHeaders('lastModified', HeaderConstants.LAST_MODIFIED);
  setContainerPropertyFromHeaders('lease.status', HeaderConstants.LEASE_STATUS);
  setContainerPropertyFromHeaders('lease.state', HeaderConstants.LEASE_STATE);
  setContainerPropertyFromHeaders('lease.duration', HeaderConstants.LEASE_DURATION);
  setContainerPropertyFromHeaders('requestId', HeaderConstants.REQUEST_ID);
 
  if (!self.publicAccessLevel) {
    self.publicAccessLevel = BlobUtilities.BlobContainerPublicAccessType.OFF;
    if (headers[HeaderConstants.BLOB_PUBLIC_ACCESS]) {
      self.publicAccessLevel = headers[HeaderConstants.BLOB_PUBLIC_ACCESS];
    }
  }
 
  if (self.publicAccessLevel === 'true') {
    // The container was marked for full public read access using a version prior to 2009-09-19.
    self.publicAccessLevel = BlobUtilities.BlobContainerPublicAccessType.CONTAINER;
  }
};
 
/**
* The container ACL settings.
* @typedef    {object}                        ContainerAclResult
* @extends    {ContainerResult}
* @property   {Object.<string, AccessPolicy>}    signedIdentifiers   The container ACL settings. See `[AccessPolicy]{@link AccessPolicy}` for detailed information.
*/
 
module.exports = ContainerResult;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/models/leaseresult.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/blob/models/leaseresult.js

Statements: 25% (5 / 20)      Branches: 0% (0 / 16)      Functions: 0% (0 / 2)      Lines: 25% (5 / 20)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74                                  1 1                                         1                                   1                             1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var Constants = require('./../../../common/common').Constants;
var HeaderConstants = Constants.HeaderConstants;
 
 
/**
* Creates a new LeaseResult object.
* @class
* The LeaseResult class is used to store the lease information.
* 
 * @property  {string}                      container                         The container name.
 * @property  {string}                      blob                              The blob name.
 * @property  {string}                      id                                The lease id.
 * @property  {string}                      time                              Approximate time remaining in the lease period, in seconds.
 * @property  {string}                      etag                              The etag.
 * @property  {string}                      lastModified                      The date/time that the lease was last modified.
 * 
* @constructor
* @param {string} [container]               The container name.
* @param {string} [blob]                    The blob name.
* @param {string} [id]                      The lease id.
* @param {string} [time]                    Approximate time remaining in the lease period, in seconds.
*/
function LeaseResult(container, blob, id, time) {
  if (container) {
    this.container = container;
  }
 
  if (blob) {
    this.blob = blob;
  }
 
  if (id) {
    this.id = id;
  }
 
  if (time) {
    this.time = time;
  }
}
 
LeaseResult.prototype.getPropertiesFromHeaders = function (headers) {
  var self = this;
 
  if (!self['id'] && headers[HeaderConstants.LEASE_ID]) {
    self['id'] = headers[HeaderConstants.LEASE_ID];
  }
 
  if (!self['time'] && headers[HeaderConstants.LEASE_TIME]) {
    self['time'] = parseInt(headers[HeaderConstants.LEASE_TIME], 10);
  }
 
  self['etag'] = headers[HeaderConstants.ETAG];
  self['lastModified'] = headers[HeaderConstants.LAST_MODIFIED.toLowerCase()];
};
 
module.exports = LeaseResult;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/file/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/file/

Statements: 6.96% (102 / 1465)      Branches: 0% (0 / 368)      Functions: 0% (0 / 267)      Lines: 7.45% (102 / 1370)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/lib/services/file/
File Statements Branches Functions Lines
fileservice.js 6.77% (99 / 1462) 0% (0 / 368) 0% (0 / 267) 7.24% (99 / 1367)
fileutilities.js 100% (3 / 3) 100% (0 / 0) 100% (0 / 0) 100% (3 / 3)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/file/fileservice.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/file/fileservice.js

Statements: 6.77% (99 / 1462)      Branches: 0% (0 / 368)      Functions: 0% (0 / 267)      Lines: 7.24% (99 / 1367)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945                                  1 1 1 1 1 1 1   1 1 1 1 1 1 1 1     1 1 1 1 1     1 1 1 1 1 1 1     1 1 1 1     1 1                                                           1                           1                         1                                                                                                           1                                                 1                                                           1                                                           1                                                                                                                                                                               1                                                       1                                                                                                                                           1                                                                                                                             1                                                                                                               1                                                                                                               1                                                                                                               1                                                                                                                   1                                                                                                               1                                                                                                             1                                                                                                                                     1                                                                                               1                                                                                                                       1                                                       1                                                                                                                                     1                                                                                                                             1                                                                                                             1                                                                                                 1                                                                                                                         1                                                           1                                                                                                                                                                                                                 1                                                                                                                 1                                                                                                                           1                                                                                                                                         1                                                                                             1                                                                                                                     1                                                                                                                                         1                                                                                                                         1                                                                                                                     1                                                                                                                       1                                                                       1                                                                                                                   1                                                                                                     1                                                                                                                               1                                                                                                                                                                           1                                                                                                                                             1                                                                                                                                           1                                                                                                                                                           1                                                                                                                                                           1                                                                                                                           1                                                                                                                                           1                                                                                                                                               1                                                                                                                                               1                                                                                                                                                     1                                                                                                                                     1                                                                                                                                   1                                                                                                                               1                                                                                                                             1                                                                                                                               1                                                                                                                                                                                                                                                                                     1                                                                                                                                                 1                                                                                                                                                                                                                                                                                                         1                                   1                                                 1                                                                                                                                         1                                                                                                                                     1                                                                                                                                     1                                                                                                   1   1    
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var fs = require('fs');
var qs = require('querystring');
var url = require('url');
var util = require('util');
var _ = require('underscore');
var extend = require('extend');
var path = require('path');
 
var azureCommon = require('./../../common/common');
var Md5Wrapper = require('./../../common/md5-wrapper');
var azureutil = azureCommon.util;
var SR = azureCommon.SR;
var validate = azureCommon.validate;
var SpeedSummary = azureCommon.SpeedSummary;
var StorageServiceClient = azureCommon.StorageServiceClient;
var WebResource = azureCommon.WebResource;
 
// Constants
var Constants = azureCommon.Constants;
var FileConstants = Constants.FileConstants;
var HeaderConstants = Constants.HeaderConstants;
var HttpConstants = Constants.HttpConstants;
var QueryStringConstants = Constants.QueryStringConstants;
 
// Streams
var BatchOperation = azureCommon.BatchOperation;
var SpeedSummary = azureCommon.SpeedSummary;
var ChunkAllocator = azureCommon.ChunkAllocator;
var ChunkStream = azureCommon.ChunkStream;
var ChunkStreamWithStream = azureCommon.ChunkStreamWithStream;
var FileReadStream = azureCommon.FileReadStream;
var FileRangeStream = require('./internal/filerangestream');
 
// Models requires
var ShareResult = require('./models/shareresult');
var DirectoryResult = require('./models/directoryresult');
var FileResult = require('./models/fileresult');
var AclResult = azureCommon.AclResult;
 
// Errors requires
var errors = require('../../common/errors/errors');
var ArgumentNullError = errors.ArgumentNullError;
 
/**
* Creates a new FileService object.
* If no connection string or storageaccount and storageaccesskey are provided,
* the AZURE_STORAGE_CONNECTION_STRING or AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables will be used.
* @class
* The FileService class is used to perform operations on the Microsoft Azure File Service.
* The File Service provides storage for binary large objects, and provides functions for working with data stored in files.
* 
* For more information on the File Service, as well as task focused information on using it in a Node.js application, see
* [How to Use the File Service from Node.js](http://azure.microsoft.com/en-us/documentation/articles/storage-nodejs-how-to-use-file-storage/).
* The following defaults can be set on the file service.
* defaultTimeoutIntervalInMs                          The default timeout interval, in milliseconds, to use for request made via the file service.
* defaultClientRequestTimeoutInMs                     The default timeout of client requests, in milliseconds, to use for the request made via the file service.
* defaultMaximumExecutionTimeInMs                     The default maximum execution time across all potential retries, for requests made via the file service.
* defaultLocationMode                                 The default location mode for requests made via the file service.
* parallelOperationThreadCount                        The number of parallel operations that may be performed when uploading a file.
* useNagleAlgorithm                                   Determines whether the Nagle algorithm is used for requests made via the file service; true to use the  
*                                                     Nagle algorithm; otherwise, false. The default value is false.
* @constructor
* @extends {StorageServiceClient}
*
* @param {string} [storageAccountOrConnectionString]  The storage account or the connection string.
* @param {string} [storageAccessKey]                  The storage access key.
* @param {string|object} [host]                       The host address. To define primary only, pass a string. 
*                                                     Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host.
* @param {string} [sasToken]                          The Shared Access Signature token.
* @param {string} [endpointSuffix]                    The endpoint suffix.
*/
function FileService(storageAccountOrConnectionString, storageAccessKey, host, sasToken, endpointSuffix) {
  var storageServiceSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey, host, sasToken, endpointSuffix);
 
  FileService['super_'].call(this,
    storageServiceSettings._name,
    storageServiceSettings._key,
    storageServiceSettings._fileEndpoint,
    storageServiceSettings._usePathStyleUri,
    storageServiceSettings._sasToken);
 
  this.singleFileThresholdInBytes = FileConstants.DEFAULT_SINGLE_FILE_GET_THRESHOLD_IN_BYTES;
  this.parallelOperationThreadCount = Constants.DEFAULT_PARALLEL_OPERATION_THREAD_COUNT;
}
 
util.inherits(FileService, StorageServiceClient);
 
// Utility methods
 
/**
* Create resource name
* @ignore
*
* @param {string} share          Share name
* @param {string} [directory]    Directory name
* @param {string} [file]         File name
* @return {string} The encoded resource name.
*/
function createResourceName(share, directory, file, forSAS) {
  var encode = function(name) {
    if (name && !forSAS) {
      name = encodeURIComponent(name);
      name = name.replace(/%2F/g, '/');
      name = name.replace(/%5C/g, '/');
      name = name.replace(/\+/g, '%20');
    }
    return name;
  };
 
  var name = share;
 
  if (directory) {
    // if directory does not start with '/', add it
    if (directory[0] !== '/') {
      name += ('/');
    }
 
    name += encode(directory);
  } 
 
  if (file) {
    // if the current path does not end with '/', add it
    if (name[name.length - 1] !== '/') {
      name += ('/');
    }
    
    name += encode(file);
  }
 
  return path.normalize(name).replace(/\\/g, '/');
}
 
// File service methods
 
/**
* Gets the properties of a storage account's File service, including Azure Storage Analytics.
*
* @this {FileService}
* @param {object}       [options]                               The request options.
* @param {LocationMode} [options.locationMode]                  Specifies the location mode used to decide which location the request should be sent to. 
*                                                               Please see StorageUtilities.LocationMode for the possible values.
* @param {int}          [options.timeoutIntervalInMs]           The server timeout interval, in milliseconds, to use for the request.
* @param {int}          [options.clientRequestTimeoutInMs]      The timeout of client requests, in milliseconds, to use for the request.
* @param {int}          [options.maximumExecutionTimeInMs]      The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                               The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                               execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}       [options.clientRequestId]               A string that represents the client request ID with a 1KB character limit.
* @param {bool}         [options.useNagleAlgorithm]             Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                               The default value is false.
* @param {errorOrResult}  callback                              `error` will contain information if an error occurs; otherwise, `[result]{@link ServiceProperties}` will contain the properties 
*                                                               and `response` will contain information related to this operation.
*/
FileService.prototype.getServiceProperties = function (optionsOrCallback, callback) {
  return this.getAccountServiceProperties(optionsOrCallback, callback);
};
 
/**
* Sets the properties of a storage account's File service, including Azure Storage Analytics.
* You can also use this operation to set the default request version for all incoming requests that do not have a version specified.
*
* @this {FileService}
* @param {object}             serviceProperties                        The service properties.
* @param {object}             [options]                                The request options.
* @param {LocationMode}       [options.locationMode]                   Specifies the location mode used to decide which location the request should be sent to. 
*                                                                      Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]            The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]       The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]       The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                      The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                      execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]              Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                      The default value is false.
* @param {errorOrResponse}    callback                                 `error` will contain information
*                                                                      if an error occurs; otherwise, `response`
*                                                                      will contain information related to this operation.
*/
FileService.prototype.setServiceProperties = function (serviceProperties, optionsOrCallback, callback) {
  return this.setAccountServiceProperties(serviceProperties, optionsOrCallback, callback);
};
 
// Share methods
 
/**
* Lists a segment containing a collection of share items under the specified account.
*
* @this {FileService}
* @param {object}             currentToken                                A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {object}             [options]                                   The request options.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.maxResults]                        Specifies the maximum number of shares to return per call to Azure storage.
* @param {string}             [options.include]                           Include this parameter to specify that the share's metadata be returned as part of the response body. (allowed values: '', 'metadata')
*                                                                         **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. 
*                                                                         `entries`  gives a list of `[shares]{@link ShareResult}` and the `continuationToken` is used for the next listing operation.
*                                                                         `response` will contain information related to this operation.
*/
FileService.prototype.listSharesSegmented = function (currentToken, optionsOrCallback, callback) {
  this.listSharesSegmentedWithPrefix(null /* prefix */, currentToken, optionsOrCallback, callback);
};
 
/**
* Lists a segment containing a collection of share items whose names begin with the specified prefix under the specified account.
*
* @this {FileService}
* @param {string}             prefix                                      The prefix of the share name.
* @param {object}             currentToken                                A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {object}             [options]                                   The request options.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {string}             [options.prefix]                            Filters the results to return only shares whose name begins with the specified prefix.
* @param {int}                [options.maxResults]                        Specifies the maximum number of shares to return per call to Azure storage.
* @param {string}             [options.include]                           Include this parameter to specify that the share's metadata be returned as part of the response body. (allowed values: '', 'metadata')
*                                                                         **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. 
*                                                                         `entries`  gives a list of `[shares]{@link ShareResult}` and the `continuationToken` is used for the next listing operation.
*                                                                         `response` will contain information related to this operation.
*/
FileService.prototype.listSharesSegmentedWithPrefix = function (prefix, currentToken, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  
  validate.validateArgs('listShares', function (v) {
    v.callback(callback);
  });
  
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.get()
    .withQueryOption(QueryStringConstants.COMP, 'list')
    .withQueryOption(QueryStringConstants.MAX_RESULTS, options.maxResults)
    .withQueryOption(QueryStringConstants.INCLUDE, options.include);
  
  if (!azureutil.objectIsNull(currentToken)) {
    webResource.withQueryOption(QueryStringConstants.MARKER, currentToken.nextMarker);
  }
  
  webResource.withQueryOption(QueryStringConstants.PREFIX, prefix);
  
  //options.requestLocationMode = azureutil.getNextListingLocationMode(currentToken);
  
  var processResponseCallback = function (responseObject, next) {
    responseObject.listSharesResult = null;
    
    if (!responseObject.error) {
      responseObject.listSharesResult = {
        entries: null,
        continuationToken: null
      };
      responseObject.listSharesResult.entries = [];
      
      var shares = [];
      
      if (responseObject.response.body.EnumerationResults.Shares && responseObject.response.body.EnumerationResults.Shares.Share) {
        shares = responseObject.response.body.EnumerationResults.Shares.Share;
        if (!_.isArray(shares)) {
          shares = [shares];
        }
      }
      
      shares.forEach(function (currentShare) {
        var shareResult = ShareResult.parse(currentShare);
        responseObject.listSharesResult.entries.push(shareResult);
      });
      
      if (responseObject.response.body.EnumerationResults.NextMarker) {
        responseObject.listSharesResult.continuationToken = {
          nextMarker: null,
          targetLocation: null
        };
        
        responseObject.listSharesResult.continuationToken.nextMarker = responseObject.response.body.EnumerationResults.NextMarker;
        responseObject.listSharesResult.continuationToken.targetLocation = responseObject.targetLocation;
      }
    }
    
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.listSharesResult, returnObject.response);
    };
    
    next(responseObject, finalCallback);
  };
  
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Checks whether or not a share exists on the service.
*
* @this {FileService}
* @param {string}             share                                   The share name.
* @param {object}             [options]                               The request options.
* @param {LocationMode}       [options.locationMode]                  Specifies the location mode used to decide which location the request should be sent to. 
*                                                                     Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]           The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]      The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]      The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                     The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                     execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]               A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]             Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                     The default value is false.
* @param {errorOrResult}      callback                                `error` will contain information
*                                                                     if an error occurs; otherwise `[result]{@link ShareResult}` will contain
*                                                                     the share information including `exists` boolean member. 
*                                                                     `response` will contain information related to this operation.
*/
FileService.prototype.doesShareExist = function (share, optionsOrCallback, callback) {
  this._doesShareExist(share, false, optionsOrCallback, callback);
};
 
/**
* Creates a new share under the specified account.
* If a share with the same name already exists, the operation fails.
*
* @this {FileService}
* @param {string}             share                               The share name.
* @param {object}             [options]                           The request options.
* @param {int}                [options.quota]                     Specifies the maximum size of the share, in gigabytes.
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {object}             [options.metadata]                  The metadata key/value pairs.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.   
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise `[result]{@link ShareResult}` will contain
*                                                                 the share information.
*                                                                 `response` will contain information related to this operation.
*/
FileService.prototype.createShare = function (share, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('createShare', function (v) {
    v.string(share, 'share');
    v.shareNameIsValid(share);
    v.shareQuotaIsValid(userOptions.quota);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.put(share)
    .withQueryOption(QueryStringConstants.RESTYPE, 'share')
    .withHeader(HeaderConstants.SHARE_QUOTA, options.quota);
 
  webResource.addOptionalMetadataHeaders(options.metadata);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.shareResult = null;
    if (!responseObject.error) {
      responseObject.shareResult = new ShareResult(share);
      responseObject.shareResult.getPropertiesFromHeaders(responseObject.response.headers);
 
      if (options.metadata) {
        responseObject.shareResult.metadata = options.metadata;
      }
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.shareResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Creates a new share under the specified account if the share does not exists.
*
* @this {FileService}
* @param {string}             share                                     The share name.
* @param {object}             [options]                                 The request options.
* @param {LocationMode}       [options.locationMode]                    Specifies the location mode used to decide which location the request should be sent to. 
*                                                                       Please see StorageUtilities.LocationMode for the possible values.
* @param {object}             [options.metadata]                        The metadata key/value pairs.
* @param {int}                [options.timeoutIntervalInMs]             The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]        The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]        The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                       The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                       execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                 A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]               Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                       The default value is false.
* @param {errorOrResult}      callback                                  `error` will contain information
*                                                                       if an error occurs; otherwise `[result]{@link ShareResult}` will contain
*                                                                       the share information including `created` boolean member.
*                                                                       `response` will contain information related to this operation.
*
* @example
* var azure = require('azure-storage');
* var FileService = azure.createFileService();
* FileService.createShareIfNotExists('taskshare', function(error) {
*   if(!error) {
*     // Share created or already existed
*   }
* }); 
*/
FileService.prototype.createShareIfNotExists = function (share, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('createShareIfNotExists', function (v) {
    v.string(share, 'share');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var self = this;
  self._doesShareExist(share, true, options, function(error, result, response) {
    var exists = result.exists;
    result.created = false;
    delete result.exists;
    
    if(error){
      callback(error, result, response);
    } else if (exists) {
      response.isSuccessful = true;
      callback(error, result, response);
    } else {
      self.createShare(share, options, function (createError, responseShare, createResponse) {
        if(!createError){
          responseShare.created = true;
        }
        else if (createError && createError.statusCode === HttpConstants.HttpResponseCodes.Conflict && createError.code === Constants.FileErrorCodeStrings.SHARE_ALREADY_EXISTS) {
          // If it was created before, there was no actual error.
          createError = null;
          createResponse.isSuccessful = true;
        }
 
        callback(createError, responseShare, createResponse);
      });
    }
  });
};
 
/**
* Retrieves a share and its properties from a specified account.
* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive.
 
 
*
* @this {FileService}
* @param {string}             share                               The share name.
* @param {object}             [options]                           The request options.
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise `[result]{@link ShareResult}` will contain
*                                                                 information for the share.
*                                                                 `response` will contain information related to this operation.
*/
FileService.prototype.getShareProperties = function (share, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('getShareProperties', function (v) {
    v.string(share, 'share');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.head(share)
    .withQueryOption(QueryStringConstants.RESTYPE, 'share');
 
  //options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
 
  var self = this;
  var processResponseCallback = function (responseObject, next) {
    responseObject.shareResult = null;
    if (!responseObject.error) {
      responseObject.shareResult = new ShareResult(share);
      responseObject.shareResult.metadata = self.parseMetadataHeaders(responseObject.response.headers);
      responseObject.shareResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.shareResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Sets the properties for the specified share.
*
* @this {FileService}
* @param {string}             share                                       The share name.
* @param {object}             [properties]                                The share properties to set.
* @param {string|int}         [properties.quota]                          Specifies the maximum size of the share, in gigabytes.
* @param {object}             [options]                                   The request options.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `[share]{@link ShareResult}` will contain
*                                                                         information about the share.
*                                                                         `response` will contain information related to this operation.
*/
FileService.prototype.setShareProperties = function (share, properties, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  
  validate.validateArgs('setShareProperties', function (v) {
    v.string(share, 'share');
    v.shareNameIsValid(share);
    v.shareQuotaIsValid(userOptions.quota);
    v.callback(callback);
  });
  
  var options = extend(true, properties, userOptions);
  var resourceName = createResourceName(share);
  var webResource = WebResource.put(resourceName)
    .withQueryOption(QueryStringConstants.RESTYPE, 'share')
    .withQueryOption(QueryStringConstants.COMP, 'properties')
    .withHeader(HeaderConstants.SHARE_QUOTA, options.quota);
  
  FileResult.setProperties(webResource, options);
  
  var processResponseCallback = function (responseObject, next) {
    responseObject.shareResult = null;
    if (!responseObject.error) {
      responseObject.shareResult = new ShareResult(share);
      responseObject.shareResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
    
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.shareResult, returnObject.response);
    };
    
    next(responseObject, finalCallback);
  };
  
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Gets the share statistics for a share.
*
* @this {FileService}
* @param {string}           share                                   The share name.
* @param {object}           [options]                               The request options.
* @param {LocationMode}     [options.locationMode]                  Specifies the location mode used to decide which location the request should be sent to. 
*                                                                   Please see StorageUtilities.LocationMode for the possible values.
* @param {int}              [options.timeoutIntervalInMs]           The timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]    The timeout of client requests, in milliseconds, to use for the request.
* @param {int}              [options.maximumExecutionTimeInMs]      The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                   The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                   execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}           [options.clientRequestId]               A string that represents the client request ID with a 1KB character limit.
* @param {bool}             [options.useNagleAlgorithm]             Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                   The default value is false.
* @param {errorOrResult}    callback                                `error` will contain information if an error occurs; otherwise, `[result]{@link ServiceStats}` will contain the stats and 
*                                                                   `response` will contain information related to this operation.
*/
FileService.prototype.getShareStats = function (share, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  
  validate.validateArgs('getShareStats', function (v) {
    v.callback(callback);
  });
  
  var options = extend(true, {}, userOptions);
  var resourceName = createResourceName(share);
  var webResource = WebResource.get(resourceName)
    .withQueryOption(QueryStringConstants.RESTYPE, 'share')
    .withQueryOption(QueryStringConstants.COMP, 'stats');
  
  var processResponseCallback = function (responseObject, next) {
    responseObject.shareResult = null;
    if (!responseObject.error) {
      responseObject.shareResult = ShareResult.parse(responseObject.response.body, share);
      responseObject.shareResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
    
    // function to be called after all filters
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.shareResult, returnObject.response);
    };
    
    // call the first filter
    next(responseObject, finalCallback);
  };
  
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
 
/**
* Returns all user-defined metadata for the share.
* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive.
*
* @this {FileService}
* @param {string}             share                                     The share name.
* @param {object}             [options]                                 The request options.
* @param {LocationMode}       [options.locationMode]                    Specifies the location mode used to decide which location the request should be sent to. 
*                                                                       Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]             The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]        The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]        The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                       The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                       execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                 A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]               Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                       The default value is false.
* @param {errorOrResult}      callback                                  `error` will contain information
*                                                                       if an error occurs; otherwise `[result]{@link ShareResult}` will contain
*                                                                       information for the share.
*                                                                       `response` will contain information related to this operation.
*/
FileService.prototype.getShareMetadata = function (share, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('getShareMetadata', function (v) {
    v.string(share, 'share');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.head(share)
    .withQueryOption(QueryStringConstants.RESTYPE, 'share')
    .withQueryOption(QueryStringConstants.COMP, 'metadata');
 
  var self = this;
  var processResponseCallback = function (responseObject, next) {
    responseObject.shareResult = null;
    if (!responseObject.error) {
      responseObject.shareResult = new ShareResult(share);
      responseObject.shareResult.metadata = self.parseMetadataHeaders(responseObject.response.headers);
      responseObject.shareResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.shareResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Sets the share's metadata.
*
* Calling the Set Share Metadata operation overwrites all existing metadata that is associated with the share.
* It's not possible to modify an individual name/value pair.
*
* @this {FileService}
* @param {string}             share                               The share name.
* @param {object}             metadata                            The metadata key/value pairs.
* @param {object}             [options]                           The request options.
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResponse}  callback                              `error` will contain information
*                                                                 if an error occurs; otherwise 
*                                                                 `response` will contain information related to this operation.
*/
FileService.prototype.setShareMetadata = function (share, metadata, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('setShareMetadata', function (v) {
    v.string(share, 'share');
    v.object(metadata, 'metadata');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.put(share)
    .withQueryOption(QueryStringConstants.RESTYPE, 'share')
    .withQueryOption(QueryStringConstants.COMP, 'metadata');
 
  webResource.addOptionalMetadataHeaders(metadata);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.shareResult = null;
    if (!responseObject.error) {
      responseObject.shareResult = new ShareResult(share);
      responseObject.shareResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.shareResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Gets the share's ACL.
*
* @this {FileService}
* @param {string}             share                               The share name.
* @param {object}             [options]                           The request options.
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise `[result]{@link ShareAclResult}` will contain
*                                                                 information for the share.
*                                                                 `response` will contain information related to this operation.
*/
FileService.prototype.getShareAcl = function (share, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  
  validate.validateArgs('getShareAcl', function (v) {
    v.string(share, 'share');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
  
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.get(share)
    .withQueryOption(QueryStringConstants.RESTYPE, 'share')
    .withQueryOption(QueryStringConstants.COMP, 'acl');
  
  options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
  
  var processResponseCallback = function (responseObject, next) {
    responseObject.shareResult = null;
    if (!responseObject.error) {
      responseObject.shareResult = new ShareResult(share);
      responseObject.shareResult.getPropertiesFromHeaders(responseObject.response.headers);
      responseObject.shareResult.signedIdentifiers = AclResult.parse(responseObject.response.body);
    }
    
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.shareResult, returnObject.response);
    };
    
    next(responseObject, finalCallback);
  };
  
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Updates the share's ACL.
*
* @this {FileService}
* @param {string}                         share                               The share name.
* @param {Object.<string, AccessPolicy>}  signedIdentifiers                   The share ACL settings. See `[AccessPolicy]{@link AccessPolicy}` for detailed information.
* @param {object}                         [options]                           The request options.
* @param {int}                            [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                            [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                            [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                             The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                             execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}                         [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}                           [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                             The default value is false.
* @param {errorOrResult}                  callback                            `error` will contain information
*                                                                             if an error occurs; otherwise `[result]{@link ShareAclResult}` will contain
*                                                                             information for the share.
*                                                                             `response` will contain information related to this operation.
*/
FileService.prototype.setShareAcl = function (share, signedIdentifiers, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  
  validate.validateArgs('setShareAcl', function (v) {
    v.string(share, 'share');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
  
  var options = extend(true, {}, userOptions);
  
  var policies = null;
  if (signedIdentifiers) {
    if(_.isArray(signedIdentifiers)) {
      throw new TypeError(SR.INVALID_SIGNED_IDENTIFIERS);
    }
    policies = AclResult.serialize(signedIdentifiers);
  }
  
  var webResource = WebResource.put(share)
    .withQueryOption(QueryStringConstants.RESTYPE, 'share')
    .withQueryOption(QueryStringConstants.COMP, 'acl')
    .withHeader(HeaderConstants.CONTENT_LENGTH, !azureutil.objectIsNull(policies) ? Buffer.byteLength(policies) : 0)
    .withBody(policies);
  
  var processResponseCallback = function (responseObject, next) {
    responseObject.shareResult = null;
    if (!responseObject.error) {
      responseObject.shareResult = new ShareResult(share);
      responseObject.shareResult.getPropertiesFromHeaders(responseObject.response.headers);
      if (signedIdentifiers) {
        responseObject.shareResult.signedIdentifiers = signedIdentifiers;
      }
    }
    
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.shareResult, returnObject.response);
    };
    
    next(responseObject, finalCallback);
  };
  
  this.performRequest(webResource, webResource.body, options, processResponseCallback);
};
 
/**
* Marks the specified share for deletion.
* The share and any files contained within it are later deleted during garbage collection.
*
* @this {FileService}
* @param {string}             share                               The share name.
* @param {object}             [options]                           The request options.
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResponse}  callback                              `error` will contain information
*                                                                 if an error occurs; otherwise
*                                                                 `response` will contain information related to this operation.
*/
FileService.prototype.deleteShare = function (share, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('deleteShare', function (v) {
    v.string(share, 'share');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.del(share)
    .withQueryOption(QueryStringConstants.RESTYPE, 'share');
  
  var processResponseCallback = function (responseObject, next) {
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Marks the specified share for deletion if it exists.
* The share and any files contained within it are later deleted during garbage collection.
*
* @this {FileService}
* @param {string}             share                               The share name.
* @param {object}             [options]                           The request options.
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise `result` will 
*                                                                 be true if the share exists and was deleted, or false if the share
*                                                                 did not exist.
*                                                                 `response` will contain information related to this operation.
*/
FileService.prototype.deleteShareIfExists = function (share, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('deleteShareIfExists', function (v) {
    v.string(share, 'share');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var self = this;
  self._doesShareExist(share, true, options, function (error, result, response) {
    if(error){
      callback(error, result.exists, response);
    } else if (!result.exists) {
      response.isSuccessful = true;
      callback(error, false, response);
    } else {
      self.deleteShare(share, options, function (deleteError, deleteResponse) {
        var deleted;
        if (!deleteError){
          deleted = true;
        } else if (deleteError && deleteError.statuscode === HttpConstants.HttpResponseCodes.NotFound && deleteError.code === Constants.FileErrorCodeStrings.SHARE_NOT_FOUND) {
          // If it was deleted already, there was no actual error.
          deleted = false;
          deleteError = null;
          deleteResponse.isSuccessful = true;
        }
 
        callback(deleteError, deleted, deleteResponse);
      });
    }
  });
};
 
// Directory methods
 
/**
* Checks whether or not a directory exists on the service.
*
* @this {FileService}
* @param {string}             share                                   The share name.
* @param {string}             directory                               The directory name. Use '' to refer to the base directory.
* @param {object}             [options]                               The request options.
* @param {LocationMode}       [options.locationMode]                  Specifies the location mode used to decide which location the request should be sent to. 
*                                                                     Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]           The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]      The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]      The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                     The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                     execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]               A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]             Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                     The default value is false.
* @param {errorOrResult}      callback                                `error` will contain information
*                                                                     if an error occurs; otherwise `[result]{@link DirectoryResult}` will contain
*                                                                     the directory information including `exists` boolean member.
*                                                                     `response` will contain information related to this operation.
*/
FileService.prototype.doesDirectoryExist = function (share, directory, optionsOrCallback, callback) {
  this._doesDirectoryExist(share, directory, false, optionsOrCallback, callback);
};
 
/**
* Creates a new directory under the specified account.
* If a directory with the same name already exists, the operation fails.
*
* @this {FileService}
* @param {string}             share                               The share name.
* @param {string}             directory                           The directory name.
* @param {object}             [options]                           The request options.
* @param {object}             [options.metadata]                  The metadata key/value pairs.
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.    
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise `[result]{@link DirectoryResult}` will contain
*                                                                 the directory information.
*                                                                 `response` will contain information related to this operation.
*/
FileService.prototype.createDirectory = function (share, directory, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('createDirectory', function (v) {
    v.string(share, 'share');
    v.string(directory, 'directory');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.put(createResourceName(share, directory))
    .withQueryOption(QueryStringConstants.RESTYPE, 'directory');
 
  webResource.addOptionalMetadataHeaders(options.metadata);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.directoryResult = null;
    if (!responseObject.error) {
      responseObject.directoryResult = new DirectoryResult(directory);
      responseObject.directoryResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.directoryResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Creates a new directory under the specified account if the directory does not exists.
*
* @this {FileService}
* @param {string}             share                                     The share name.
* @param {string}             directory                                 The directory name.
* @param {object}             [options]                                 The request options.
* @param {object}             [options.metadata]                        The metadata key/value pairs.
* @param {LocationMode}       [options.locationMode]                    Specifies the location mode used to decide which location the request should be sent to. 
*                                                                       Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]             The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]        The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]        The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                       The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                       execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                 A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]               Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                       The default value is false.
* @param {errorOrResult}      callback                                  `error` will contain information
*                                                                       if an error occurs; otherwise `[result]{@link DirectoryResult}` will contain
*                                                                       the directory information including `created` boolean member.
*                                                                       already exists.
*                                                                       `response` will contain information related to this operation.
*
* @example
* var azure = require('azure-storage');
* var FileService = azure.createFileService();
* FileService.createDirectoryIfNotExists('taskshare', taskdirectory', function(error) {
*   if(!error) {
*     // Directory created or already existed
*   }
* }); 
*/
FileService.prototype.createDirectoryIfNotExists = function (share, directory, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('createDirectoryIfNotExists', function (v) {
    v.string(share, 'share');
    v.string(directory, 'directory');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var self = this;
  self._doesDirectoryExist(share, directory, true, options, function(error, result, response) {
    var exists = result.exists;
    result.created = false;
    delete result.exists;
    
    if(error){
      callback(error, result, response);
    } else if (exists) {
      response.isSuccessful = true;
      callback(error, result, response);
    } else {
      self.createDirectory(share, directory, options, function (createError, responseDirectory, createResponse) {
        if(!createError){
          responseDirectory.created = true;
        }
        else if (createError && createError.statusCode === HttpConstants.HttpResponseCodes.Conflict && createError.code === Constants.StorageErrorCodeStrings.RESOURCE_ALREADY_EXISTS) {
          // If it was created before, there was no actual error.
          createError = null;
          createResponse.isSuccessful = true;
        }
 
        callback(createError, responseDirectory, createResponse);
      });
    }
  });
};
 
/**
* Retrieves a directory and its properties from a specified account.
* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive.
*
* @this {FileService}
* @param {string}             share                               The share name.
* @param {string}             directory                           The directory name. Use '' to refer to the base directory.
* @param {object}             [options]                           The request options.
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise `[result]{@link DirectoryResult}` will contain
*                                                                 information for the directory.
*                                                                 `response` will contain information related to this operation.
*/
FileService.prototype.getDirectoryProperties = function (share, directory, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('getDirectoryProperties', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.head(createResourceName(share, directory))
    .withQueryOption(QueryStringConstants.RESTYPE, 'directory');
  
  var self = this;
  var processResponseCallback = function (responseObject, next) {
    responseObject.directoryResult = null;
    if (!responseObject.error) {
      responseObject.directoryResult = new DirectoryResult(directory);
      responseObject.directoryResult.metadata = self.parseMetadataHeaders(responseObject.response.headers);
      responseObject.directoryResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.directoryResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Marks the specified directory for deletion. The directory must be empty before it can be deleted.
*
* @this {FileService}
* @param {string}             share                               The share name.
* @param {string}             directory                           The directory name.
* @param {object}             [options]                           The request options.
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResponse}  callback                              `error` will contain information
*                                                                 if an error occurs; otherwise
*                                                                 `response` will contain information related to this operation.
*/
FileService.prototype.deleteDirectory = function (share, directory, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('deleteDirectory', function (v) {
    v.string(share, 'share');
    v.string(directory, 'directory');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.del(createResourceName(share, directory))
    .withQueryOption(QueryStringConstants.RESTYPE, 'directory');
  
  var processResponseCallback = function (responseObject, next) {
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Marks the specified directory for deletion if it exists. The directory must be empty before it can be deleted.
*
* @this {FileService}
* @param {string}             share                               The share name.
* @param {string}             directory                           The directory name.
* @param {object}             [options]                           The request options.
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise `result` will 
*                                                                 be true if the directory exists and was deleted, or false if the directory
*                                                                 did not exist.
*                                                                 `response` will contain information related to this operation.
*/
FileService.prototype.deleteDirectoryIfExists = function (share, directory, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('deleteDirectoryIfExists', function (v) {
    v.string(share, 'share');
    v.string(directory, 'directory');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var self = this;
  self._doesDirectoryExist(share, directory, true, options, function(error, result, response) {
    if(error){
      callback(error, result.exists, response);
    } else if (!result.exists) {
      response.isSuccessful = true;
      callback(error, false, response);
    } else {
      self.deleteDirectory(share, directory, options, function (deleteError, deleteResponse) {
        var deleted;
        if (!deleteError){
          deleted = true;
        } else if (deleteError && deleteError.statuscode === HttpConstants.HttpResponseCodes.NotFound && deleteError.code === Constants.StorageErrorCodeStrings.RESOURCE_NOT_FOUND) {
          // If it was deleted already, there was no actual error.
          deleted = false;
          deleteError = null;
          deleteResponse.isSuccessful = true;
        }
 
        callback(deleteError, deleted, deleteResponse);
      });
    }
  });
};
 
/**
* Lists a segment containing a collection of file items in the directory.
*
* @this {FileService}
* @param {string}             share                               The share name.
* @param {string}             directory                           The directory name. Use '' to refer to the base directory.
* @param {object}             currentToken                        A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {object}             [options]                           The request options.
* @param {int}                [options.maxResults]                Specifies the maximum number of files to return per call to Azure ServiceClient. This does NOT affect list size returned by this function. (maximum: 5000)
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise `result` will contain
*                                                                 entries.files which contains a list of `[files]{@link FileResult}`, entries.directories which contains a list of `[directories]{@link DirectoryResult}` and the continuationToken for the next listing operation.
*                                                                 `response` will contain information related to this operation.
*/
FileService.prototype.listFilesAndDirectoriesSegmented = function (share, directory, currentToken, optionsOrCallback, callback) {
  this.listFilesAndDirectoriesSegmentedWithPrefix(share, directory, null /*prefix*/, currentToken, optionsOrCallback, callback);
};
 
 
/**
* Lists a segment containing a collection of file items in the directory.
*
* @this {FileService}
* @param {string}             share                               The share name.
* @param {string}             directory                           The directory name. Use '' to refer to the base directory.
* @param {string}             prefix                              The prefix of the directory/files name.
* @param {object}             currentToken                        A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {object}             [options]                           The request options.
* @param {int}                [options.maxResults]                Specifies the maximum number of files to return per call to Azure ServiceClient. This does NOT affect list size returned by this function. (maximum: 5000)
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise `result` will contain
*                                                                 entries.files which contains a list of `[files]{@link FileResult}`, entries.directories which contains a list of `[directories]{@link DirectoryResult}` and the continuationToken for the next listing operation.
*                                                                 `response` will contain information related to this operation.
*/
FileService.prototype.listFilesAndDirectoriesSegmentedWithPrefix = function (share, directory, prefix, currentToken, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('listFilesSegmented', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.get(createResourceName(share, directory))
    .withQueryOption(QueryStringConstants.RESTYPE, 'directory')
    .withQueryOption(QueryStringConstants.COMP, 'list')
    .withQueryOption(QueryStringConstants.MAX_RESULTS, options.maxResults);
 
  if (!azureutil.objectIsNull(currentToken)) {
    webResource.withQueryOption(QueryStringConstants.MARKER, currentToken.nextMarker);
  }
 
  webResource.withQueryOption(QueryStringConstants.PREFIX, prefix);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.listResult = null;
    if (!responseObject.error) {
      responseObject.listResult = {
        entries: null,
        continuationToken: null
      };
 
      responseObject.listResult.entries = {};
      responseObject.listResult.entries.files = [];
      responseObject.listResult.entries.directories = [];
      var files = [];
      var directories = [];
 
      // parse files
      if (responseObject.response.body.EnumerationResults.Entries.File) {
        files = responseObject.response.body.EnumerationResults.Entries.File;
        if (!_.isArray(files)) {
          files = [ files ];
        }
      }
 
      files.forEach(function (currentFile) {
        var fileResult = FileResult.parse(currentFile);
        responseObject.listResult.entries.files.push(fileResult);
      });
 
      // parse directories
      if (responseObject.response.body.EnumerationResults.Entries.Directory) {
        directories = responseObject.response.body.EnumerationResults.Entries.Directory;
        if (!_.isArray(directories)) {
          directories = [ directories ];
        }
      }
 
      directories.forEach(function (currentDirectory) {
        var directoryResult = DirectoryResult.parse(currentDirectory);
        responseObject.listResult.entries.directories.push(directoryResult);
      });
 
      // parse continuation token
      if(responseObject.response.body.EnumerationResults.NextMarker) {
        responseObject.listResult.continuationToken = {
          nextMarker: null,
          targetLocation: null
        };
 
        responseObject.listResult.continuationToken.nextMarker = responseObject.response.body.EnumerationResults.NextMarker;
        responseObject.listResult.continuationToken.targetLocation = responseObject.targetLocation;
      }
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.listResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Returns all user-defined metadata for the specified directory.
* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive.
*
* @this {FileService}
* @param {string}             share                                       The share name.
* @param {string}             directory                                   The directory name. Use '' to refer to the base directory.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link DirectoryResult}` will contain
*                                                                         information about the directory.
*                                                                         `response` will contain information related to this operation.
*/
FileService.prototype.getDirectoryMetadata = function (share, directory, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  
  validate.validateArgs('getDirectoryMetadata', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
  
  var options = extend(true, {}, userOptions);
  var resourceName = createResourceName(share, directory);
  var webResource = WebResource.head(resourceName)
    .withQueryOption(QueryStringConstants.RESTYPE, 'directory')
    .withQueryOption(QueryStringConstants.COMP, 'metadata');
  
  var self = this;
  var processResponseCallback = function (responseObject, next) {
    responseObject.directoryResult = null;
    if (!responseObject.error) {
      responseObject.directoryResult = new DirectoryResult(directory);
      responseObject.directoryResult.metadata = self.parseMetadataHeaders(responseObject.response.headers);
      responseObject.directoryResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
    
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.directoryResult, returnObject.response);
    };
    
    next(responseObject, finalCallback);
  };
  
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Sets user-defined metadata for the specified directory as one or more name-value pairs 
*
* @this {FileService}
* @param {string}             share                                       The share name.
* @param {string}             directory                                   The directory name. Use '' to refer to the base directory.
* @param {object}             metadata                                    The metadata key/value pairs.
* @param {object}             [options]                                   The request options.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link DirectoryResult}` will contain
*                                                                         information on the directory.
*                                                                         `response` will contain information related to this operation.
*/
FileService.prototype.setDirectoryMetadata = function (share, directory, metadata, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  
  validate.validateArgs('setDirectoryMetadata', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.shareNameIsValid(share);
    v.object(metadata, 'metadata');
    v.callback(callback);
  });
  
  var options = extend(true, {}, userOptions);
  var resourceName = createResourceName(share, directory);
  var webResource = WebResource.put(resourceName)
    .withQueryOption(QueryStringConstants.RESTYPE, 'directory')
    .withQueryOption(QueryStringConstants.COMP, 'metadata');
  
  webResource.addOptionalMetadataHeaders(metadata);
  
  var processResponseCallback = function (responseObject, next) {
    responseObject.directoryResult = null;
    if (!responseObject.error) {
      responseObject.directoryResult = new DirectoryResult(directory);
      responseObject.directoryResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
    
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.directoryResult, returnObject.response);
    };
    
    next(responseObject, finalCallback);
  };
  
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
// File methods
 
/**
* Retrieves a shared access signature token.
*
* @this {FileService}
* @param {string}                   share                                               The share name.
* @param {string}                   [directory]                                         The directory name. Use '' to refer to the base directory.
* @param {string}                   [file]                                              The file name.
* @param {object}                   sharedAccessPolicy                                  The shared access policy.
* @param {string}                   [sharedAccessPolicy.Id]                             The signed identifier.
* @param {object}                   [sharedAccessPolicy.AccessPolicy.Permissions]       The permission type.
* @param {date|string}              [sharedAccessPolicy.AccessPolicy.Start]             The time at which the Shared Access Signature becomes valid (The UTC value will be used).
* @param {date|string}              [sharedAccessPolicy.AccessPolicy.Expiry]            The time at which the Shared Access Signature becomes expired (The UTC value will be used).
* @param {string}                   [sharedAccessPolicy.AccessPolicy.IPAddressOrRange]  An IP address or a range of IP addresses from which to accept requests. When specifying a range, note that the range is inclusive.
* @param {string}                   [sharedAccessPolicy.AccessPolicy.Protocols]         The protocols permitted for a request made with the account SAS. 
*                                                                                       Possible values are both HTTPS and HTTP (https,http) or HTTPS only (https). The default value is https,http.
* @param {object}                   [headers]                                           The optional header values to set for a file returned wth this SAS.
* @param {string}                   [headers.cacheControl]                              The optional value of the Cache-Control response header to be returned when this SAS is used.
* @param {string}                   [headers.contentType]                               The optional value of the Content-Type response header to be returned when this SAS is used.
* @param {string}                   [headers.contentEncoding]                           The optional value of the Content-Encoding response header to be returned when this SAS is used.
* @param {string}                   [headers.contentLanguage]                           The optional value of the Content-Language response header to be returned when this SAS is used.
* @param {string}                   [headers.contentDisposition]                        The optional value of the Content-Disposition response header to be returned when this SAS is used.
* @return {string}                                                                      The shared access signature query string. Note this string does not contain the leading "?".
*/
FileService.prototype.generateSharedAccessSignature = function (share, directory, file, sharedAccessPolicy, headers) {
  // check if the FileService is able to generate a shared access signature
  if (!this.storageCredentials || !this.storageCredentials.generateSignedQueryString) {
    throw new Error(SR.CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY);
  }
 
  // Validate share name. File name is optional.
  validate.validateArgs('generateSharedAccessSignature', function (v) {
    v.string(share, 'share');
    v.shareNameIsValid(share);
    v.object(sharedAccessPolicy, 'sharedAccessPolicy');
  });
 
  var resourceType = FileConstants.ResourceTypes.SHARE;
  if (file) {
    validate.validateArgs('generateSharedAccessSignature', function (v) {
      v.stringAllowEmpty(directory, 'directory');
      v.string(file, 'file');
    });
    resourceType = FileConstants.ResourceTypes.FILE;
  } else {
    directory = ''; // If file is not set, directory is not a part of the string to sign.
  }
 
  if (sharedAccessPolicy.AccessPolicy) {
    if (!azureutil.objectIsNull(sharedAccessPolicy.AccessPolicy.Start)) {
      if (!_.isDate(sharedAccessPolicy.AccessPolicy.Start)) {
        sharedAccessPolicy.AccessPolicy.Start = new Date(sharedAccessPolicy.AccessPolicy.Start);
      }
 
      sharedAccessPolicy.AccessPolicy.Start = azureutil.truncatedISO8061Date(sharedAccessPolicy.AccessPolicy.Start);
    }
 
    if (!azureutil.objectIsNull(sharedAccessPolicy.AccessPolicy.Expiry)) {
      if (!_.isDate(sharedAccessPolicy.AccessPolicy.Expiry)) {
        sharedAccessPolicy.AccessPolicy.Expiry = new Date(sharedAccessPolicy.AccessPolicy.Expiry);
      }
 
      sharedAccessPolicy.AccessPolicy.Expiry = azureutil.truncatedISO8061Date(sharedAccessPolicy.AccessPolicy.Expiry);
    }
  }
 
  var resourceName = createResourceName(share, directory, file, true);
  return this.storageCredentials.generateSignedQueryString(Constants.ServiceType.File, resourceName, sharedAccessPolicy, null, { headers: headers, resourceType: resourceType });
};
 
/**
* Retrieves a file or directory URL.
*
* @param {string}                   share                    The share name.
* @param {string}                   directory                The directory name. Use '' to refer to the base directory.
* @param {string}                   [file]                   The file name. File names may not start or end with the delimiter '/'.
* @param {string}                   [sasToken]               The Shared Access Signature token.
* @param {boolean}                  [primary]                A boolean representing whether to use the primary or the secondary endpoint.
* @return {string}                                           The formatted URL string.
* @example
* var azure = require('azure-storage');
* var fileService = azure.createFileService();
* var sharedAccessPolicy = {
*   AccessPolicy: {
*     Permissions: azure.FileUtilities.SharedAccessPermissions.READ,
*     Start: startDate,
*     Expiry: expiryDate
*   },
* };
* 
* var sasToken = fileService.generateSharedAccessSignature(shareName, directoryName, fileName, sharedAccessPolicy);
* var url = fileService.getUrl(shareName, directoryName, fileName, sasToken, true);
*/
FileService.prototype.getUrl = function (share, directory, file, sasToken, primary) {
  validate.validateArgs('getUrl', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.shareNameIsValid(share);
  });
 
  var host;
  if(!azureutil.objectIsNull(primary) && primary === false) {
    host = this.host.secondaryHost;
  } else {
    host = this.host.primaryHost;
  }
  host = azureutil.trimPortFromUri(host);
  if(host && host.lastIndexOf('/') !== (host.length - 1)){
    host = host + '/';
  }
 
  var name = createResourceName(share, directory, file);
  return url.resolve(host, url.format({pathname: this._getPath(name), query: qs.parse(sasToken)}));
};
 
/**
* Returns all user-defined metadata, standard HTTP properties, and system properties for the file.
* It does not return or modify the content of the file.
* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive.
*
* @this {FileService}
* @param {string}             share                                       The share name.
* @param {string}             directory                                   The directory name. Use '' to refer to the base directory.
* @param {string}             file                                        The file name. File names may not start or end with the delimiter '/'.
* @param {object}             [options]                                   The request options.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link FileResult}` will contain
*                                                                         information about the file.
*                                                                         `response` will contain information related to this operation.
*/
FileService.prototype.getFileProperties = function (share, directory, file, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('getFileProperties', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.string(file, 'file');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var resourceName = createResourceName(share, directory, file);
  var webResource = WebResource.head(resourceName);
 
  var self = this;
  var processResponseCallback = function (responseObject, next) {
    responseObject.fileResult = null;
    if (!responseObject.error) {
      responseObject.fileResult = new FileResult(share, directory, file);
      responseObject.fileResult.metadata = self.parseMetadataHeaders(responseObject.response.headers);
      responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers, true);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.fileResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Returns all user-defined metadata for the specified file.
* It does not modify or return the content of the file.
* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive.
*
* @this {FileService}
* @param {string}             share                                       The share name.
* @param {string}             directory                                   The directory name. Use '' to refer to the base directory.
* @param {string}             file                                        The file name. File names may not start or end with the delimiter '/'.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link FileResult}` will contain
*                                                                         information about the file.
*                                                                         `response` will contain information related to this operation.
*/
FileService.prototype.getFileMetadata = function (share, directory, file, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('getFileMetadata', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.string(file, 'file');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var resourceName = createResourceName(share, directory, file);
  var webResource = WebResource.head(resourceName)
    .withQueryOption(QueryStringConstants.COMP, 'metadata');
 
  var self = this;
  var processResponseCallback = function (responseObject, next) {
    responseObject.fileResult = null;
    if (!responseObject.error) {
      responseObject.fileResult = new FileResult(share, directory, file);
      responseObject.fileResult.metadata = self.parseMetadataHeaders(responseObject.response.headers);
      responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.fileResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Sets user-defined properties for the specified file.
* It does not modify or return the content of the file.
*
* @this {FileService}
* @param {string}             share                                       The share name.
* @param {string}             directory                                   The directory name. Use '' to refer to the base directory.
* @param {string}             file                                        The file name. File names may not start or end with the delimiter '/'.
* @param {object}             [properties]                                The file properties to set.
* @param {string}             [properties.contentType]                    The MIME content type of the file. The default type is application/octet-stream.
* @param {string}             [properties.contentEncoding]                The content encodings that have been applied to the file.
* @param {string}             [properties.contentLanguage]                The natural languages used by this resource.
* @param {string}             [properties.cacheControl]                   The file's cache control.
* @param {string}             [properties.contentDisposition]             The file's content disposition.
* @param {string}             [properties.contentLength]                  Resizes a file to the specified size. If the specified byte value is less than the current size of the file, 
*                                                                         then all ranges above the specified byte value are cleared.
* @param {string}             [properties.contentMD5]                     The file's MD5 hash.
* @param {object}             [options]                                   The request options.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link FileResult}` will contain
*                                                                         information about the file.
*                                                                         `response` will contain information related to this operation.
*/
FileService.prototype.setFileProperties = function (share, directory, file, properties, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('setFileProperties', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.string(file, 'file');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {contentSettings: properties, contentLength: properties.contentLength }, userOptions);
  var resourceName = createResourceName(share, directory, file);
  var webResource = WebResource.put(resourceName)
    .withQueryOption(QueryStringConstants.COMP, 'properties');
 
  FileResult.setProperties(webResource, options);
 
  var processResponseCallback = function(responseObject, next) {
    responseObject.fileResult = null;
    if (!responseObject.error) {
      responseObject.fileResult = new FileResult(share, directory, file);
      responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
    
    var finalCallback = function(returnObject) {
      callback(returnObject.error, returnObject.fileResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
  
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Sets user-defined metadata for the specified file as one or more name-value pairs 
* It does not modify or return the content of the file.
*
* @this {FileService}
* @param {string}             share                                       The share name.
* @param {string}             directory                                   The directory name. Use '' to refer to the base directory.
* @param {string}             file                                        The file name. File names may not start or end with the delimiter '/'.
* @param {object}             metadata                                    The metadata key/value pairs.
* @param {object}             [options]                                   The request options.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link FileResult}` will contain
*                                                                         information on the file.
*                                                                         `response` will contain information related to this operation.
*/
FileService.prototype.setFileMetadata = function (share, directory, file, metadata, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('setFileMetadata', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.string(file, 'file');
    v.shareNameIsValid(share);
    v.object(metadata, 'metadata');
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var resourceName = createResourceName(share, directory, file);
  var webResource = WebResource.put(resourceName)
    .withQueryOption(QueryStringConstants.COMP, 'metadata');
 
  webResource.addOptionalMetadataHeaders(metadata);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.fileResult = null;
    if (!responseObject.error) {
      responseObject.fileResult = new FileResult(share, directory, file);
      responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.fileResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Resizes a file.
*
* @this {FileService}
* @param {string}               share                                       The share name.
* @param {string}               directory                                   The directory name. Use '' to refer to the base directory.
* @param {string}               file                                        The file name. File names may not start or end with the delimiter '/'.
* @param {String}               size                                        The size of the file, in bytes.
* @param {object}               [options]                                   The request options.
* @param {int}                  [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                  [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}               [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}                 [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}        callback                                    `error` will contain information
*                                                                           if an error occurs; otherwise `[result]{@link FileResult}` will contain
*                                                                           information about the file.
*                                                                           `response` will contain information related to this operation.
*/
FileService.prototype.resizeFile = function (share, directory, file, size, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('resizeFile', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.string(file, 'file');
    v.shareNameIsValid(share);
    v.value(size);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var resourceName = createResourceName(share, directory, file);
  var webResource = WebResource.put(resourceName)
    .withQueryOption(QueryStringConstants.COMP, 'properties');
 
  webResource.withHeader(HeaderConstants.FILE_CONTENT_LENGTH, size);
 
  var processResponseCallback = function(responseObject, next) {
    responseObject.fileResult = null;
    if (!responseObject.error) {
      responseObject.fileResult = new FileResult(share, directory, file);
      responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
    
    var finalCallback = function(returnObject) {
      callback(returnObject.error, returnObject.fileResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
  
  this.performRequest(webResource, null, options, processResponseCallback);  
};
 
/**
* Checks whether or not a file exists on the service.
*
* @this {FileService}
* @param {string}             share                                   The share name.
* @param {string}             directory                               The directory name. Use '' to refer to the base directory.
* @param {string}             file                                    The file name. File names may not start or end with the delimiter '/'.
* @param {object}             [options]                               The request options.
* @param {LocationMode}       [options.locationMode]                  Specifies the location mode used to decide which location the request should be sent to. 
*                                                                     Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]           The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]      The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]      The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                     The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                     execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]               A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]             Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                     The default value is false.
* @param {Function(error, result, response)}  callback                `error` will contain information
*                                                                     if an error occurs; otherwise `[result]{@link FileResult}` will contain
*                                                                     the file information including the `exists` boolean member. 
*                                                                     `response` will contain information related to this operation.
*/
FileService.prototype.doesFileExist = function (share, directory, file, optionsOrCallback, callback) {
  this._doesFileExist(share, directory, file, false, optionsOrCallback, callback);
};
 
/**
* Creates a file of the specified length. If the file already exists on the service, it will be overwritten.
*
* @this {FileService}
* @param {string}             share                                         The share name.
* @param {string}             directory                                     The directory name. Use '' to refer to the base directory.
* @param {string}             file                                          The file name. File names may not start or end with the delimiter '/'.
* @param {int}                length                                        The length of the file in bytes.
* @param {object}             [options]                                     The request options.
* @param {object}             [options.contentSettings]                     The file's content settings.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the file. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the file.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The file service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The file's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The file's MD5 hash.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      `error` will contain information
*                                                                           if an error occurs; otherwise `[result]{@link FileResult}` will contain
*                                                                           the file information.
*                                                                           `response` will contain information related to this operation.
*/
FileService.prototype.createFile = function (share, directory, file, length, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  validate.validateArgs('createFile', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.string(file, 'file');
    v.shareNameIsValid(share);
    v.value(length);
    v.callback(callback);
  });
 
  var resourceName = createResourceName(share, directory, file);
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.put(resourceName)
    .withHeader(HeaderConstants.TYPE, 'file')
    .withHeader(HeaderConstants.FILE_CONTENT_LENGTH, length);
 
  FileResult.setProperties(webResource, options);
 
  var processResponseCallback = function(responseObject, next) {
    responseObject.fileResult = null;
    if (!responseObject.error) {
      responseObject.fileResult = new FileResult(share, directory, file);
      responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
    
    var finalCallback = function(returnObject) {
      callback(returnObject.error, returnObject.fileResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Marks the specified file for deletion. The file is later deleted during garbage collection.
*
* @this {FileService}
* @param {string}             share                                       The share name.
* @param {string}             directory                                   The directory name. Use '' to refer to the base directory.
* @param {string}             file                                        The file name. File names may not start or end with the delimiter '/'.
* @param {object}             [options]                                   The request options.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResponse}  callback                                      `error` will contain information
*                                                                         if an error occurs; `response` will contain information related to this operation.
*/
FileService.prototype.deleteFile = function (share, directory, file, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('deleteFile', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.string(file, 'file');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var resourceName = createResourceName(share, directory, file);
  var webResource = WebResource.del(resourceName);
 
  var processResponseCallback = function (responseObject, next) {
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Marks the specified file for deletion if it exists. The file is later deleted during garbage collection.
*
* @this {FileService}
* @param {string}             share                               The share name.
* @param {string}             directory                           The directory name. Use '' to refer to the base directory.
* @param {string}             file                                The file name. File names may not start or end with the delimiter '/'. 
* @param {object}             [options]                           The request options.
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise `result` will
*                                                                 be true if the file was deleted, or false if the file
*                                                                 does not exist.
*                                                                 `response` will contain information related to this operation.
*/
FileService.prototype.deleteFileIfExists = function (share, directory, file, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('deleteFileIfExists', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.string(file, 'file');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var self = this;
  self._doesFileExist(share, directory, file, true, options, function(error, result, response) {
    if(error){
      callback(error, result.exists, response);
    } else if (!result.exists) {
      response.isSuccessful = true;
      callback(error, false, response);
    } else {
      self.deleteFile(share, directory, file, options, function (deleteError, deleteResponse) {
        var deleted;
        if (!deleteError){
          deleted = true;
        } else if (deleteError && deleteError.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound && deleteError.code === Constants.FileErrorCodeStrings.FILE_NOT_FOUND) {
          // If it was deleted already, there was no actual error.
          deleted = false;
          deleteError = null;
          deleteResponse.isSuccessful = true;
        }
 
        callback(deleteError, deleted, deleteResponse);
      });
    }
  });
};
 
/**
* Downloads a file into a text string.
*
* @this {FileService}
* @param {string}             share                                       The share name.
* @param {string}             directory                                   The directory name. Use '' to refer to the base directory.
* @param {string}             file                                        The file name. File names may not start or end with the delimiter '/'.
* @param {object}             [options]                                   The request options.
* @param {int}                [options.rangeStart]                        The range start.
* @param {int}                [options.rangeEnd]                          The range end.
* @param {boolean}            [options.disableContentMD5Validation]       When set to true, MD5 validation will be disabled when downloading files.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {FileService~FileToText}  callback                               `error` will contain information
*                                                                         if an error occurs; otherwise `text` will contain the file contents,
*                                                                         and `[file]{@link FileResult}` will contain the file information.
*                                                                         `response` will contain information related to this operation.
*/
FileService.prototype.getFileToText = function (share, directory, file, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('getFileToText', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.string(file, 'file');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var resourceName = createResourceName(share, directory, file);
  var webResource = WebResource.get(resourceName)
    .withRawResponse();
 
  FileResult.setHeaders(webResource, options);
  this._setRangeContentMD5Header(webResource, options);
 
  var self = this;
  var processResponseCallback = function (responseObject, next) {
    responseObject.text = null;
    responseObject.fileResult = null;
 
    if (!responseObject.error) {
      responseObject.fileResult = new FileResult(share, directory, file);
      responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers, true);
      responseObject.fileResult.metadata = self.parseMetadataHeaders(responseObject.response.headers);
      responseObject.text = responseObject.response.body;
 
      self._validateLengthAndMD5(options, responseObject);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.text, returnObject.fileResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Downloads an Azure file into a file.
* (Not recommended for use in the JavaScript Client Library)
*
* @this {FileService}
* @param {string}             share                                       The share name.
* @param {string}             directory                                   The directory name. Use '' to refer to the base directory.
* @param {string}             file                                        The file name. File names may not start or end with the delimiter '/'.
* @param {string}             localFileName                               The local path to the file to be downloaded.
* @param {object}             [options]                                   The request options.
* @param {boolean}            [options.skipSizeCheck]                     Skip the size check to perform direct download.
*                                                                         Set the option to true for small files.
*                                                                         Parallel download and speed summary won't work with this option on.
* @param {SpeedSummary}       [options.speedSummary]                      The download tracker objects.
* @param {int}                [options.parallelOperationThreadCount]      Parallel operation thread count.
* @param {string}             [options.rangeStart]                        Return only the bytes of the file in the specified range.
* @param {string}             [options.rangeEnd]                          Return only the bytes of the file in the specified range.
* @param {boolean}            [options.useTransactionalMD5]               When set to true, Calculate and send/validate content MD5 for transactions.
* @param {boolean}            [options.disableContentMD5Validation]       When set to true, MD5 validation will be disabled when downloading files.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information if an error occurs; 
*                                                                         otherwise `[result]{@link FileResult}` will contain the file information.
*                                                                         `response` will contain information related to this operation.
* @return {SpeedSummary}
* 
* @example
* var azure = require('azure-storage');
* var FileService = azure.createFileService();
* FileService.getFileToLocalFile('taskshare', taskdirectory', 'task1', 'task1-download.txt', function(error, serverFile) {
*   if(!error) {
*     // file available in serverFile.file variable
*   }
*/
FileService.prototype.getFileToLocalFile = function (share, directory, file, localFileName, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  userOptions.speedSummary = userOptions.speedSummary || new SpeedSummary(file);
 
  validate.validateArgs('getFileToLocalFile', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.string(file, 'file');
    v.string(localFileName, 'localFileName');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
 
  var writeStream = fs.createWriteStream(localFileName);
 
  this.getFileToStream(share, directory, file, writeStream, options, function (error, responseFile, response) {
    if (error) {
      // make sure writeStream is closed / destroyed to avoid locking issues
      if (writeStream.close) {
        writeStream.close();
      }
 
      if (azureutil.pathExistsSync(localFileName)) {
        // If the download failed from the beginning, remove the file.
        fs.unlink(localFileName, function () {
          callback(error, responseFile, response);
          return;
        });
      }
    }
    callback(error, responseFile, response); 
  });
  
  return options.speedSummary;
};
 
/**
* Provides a stream to read from a file.
*
* @this {FileService}
* @param {string}             share                                       The share name.
* @param {string}             directory                                   The directory name. Use '' to refer to the base directory.
* @param {string}             file                                        The file name. File names may not start or end with the delimiter '/'.
* @param {object}             [options]                                   The request options.
* @param {string}             [options.rangeStart]                        Return only the bytes of the file in the specified range.
* @param {string}             [options.rangeEnd]                          Return only the bytes of the file in the specified range.
* @param {boolean}            [options.useTransactionalMD5]               When set to true, Calculate and send/validate content MD5 for transactions.
* @param {boolean}            [options.disableContentMD5Validation]       When set to true, MD5 validation will be disabled when downloading files.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information if an error occurs; 
*                                                                         otherwise `[result]{@link FileResult}` will contain the file information.
*                                                                         `response` will contain information related to this operation.
* @return {Stream}
* @example
* var azure = require('azure-storage');
* var fileService = azure.createFileService();
* var writable = fs.createWriteStream(destinationFileNameTarget);
* fileService.createReadStream(shareName, directoryName, fileName).pipe(writable);
*/
FileService.prototype.createReadStream = function (share, directory, file, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('createReadStream', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.string(file, 'file');
    v.shareNameIsValid(share);
  });
 
  var options = extend(true, {}, userOptions);
 
  var readStream = new ChunkStream(options);
  this.getFileToStream(share, directory, file, readStream, options, function (error, fileResponse, response) {
    if(error) {
      readStream.emit('error', error);
    }
 
    if(callback) {
      callback(error, fileResponse, response);
    }
  });
 
  return readStream;
};
 
/**
* Downloads a file into a stream.
*
* @this {FileService}
* @param {string}             share                                       The share name.
* @param {string}             directory                                   The directory name. Use '' to refer to the base directory.
* @param {string}             file                                        The file name. File names may not start or end with the delimiter '/'.
* @param {Stream}             writeStream                                 The write stream.
* @param {object}             [options]                                   The request options.
* @param {boolean}            [options.skipSizeCheck]                     Skip the size check to perform direct download.
*                                                                         Set the option to true for small files.
*                                                                         Parallel download and speed summary won't work with this option on.
* @param {SpeedSummary}       [options.speedSummary]                      The download tracker objects.
* @param {int}                [options.parallelOperationThreadCount]      Parallel operation thread count.
* @param {string}             [options.rangeStart]                        Return only the bytes of the file in the specified range.
* @param {string}             [options.rangeEnd]                          Return only the bytes of the file in the specified range. 
* @param {boolean}            [options.useTransactionalMD5]               When set to true, Calculate and send/validate content MD5 for transactions.
* @param {boolean}            [options.disableContentMD5Validation]       When set to true, MD5 validation will be disabled when downloading files.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information if an error occurs; 
*                                                                         otherwise `[result]{@link FileResult}` will contain the file information.
*                                                                         `response` will contain information related to this operation.
* @return {SpeedSummary}
* 
*
* @example
* var azure = require('azure-storage');
* var FileService = azure.createFileService();
* FileService.getFileToStream('taskshare', taskdirectory', 'task1', fs.createWriteStream('task1-download.txt'), function(error, serverFile) {
*   if(!error) {
*     // file available in serverFile.file variable
*   }
* }); 
*/
FileService.prototype.getFileToStream = function (share, directory, file, writeStream, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  userOptions.speedSummary = userOptions.speedSummary || new SpeedSummary(file);  
  
  validate.validateArgs('getFileToStream', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.string(file, 'file');
    v.object(writeStream, 'writeStream');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
 
  var propertiesRequestOptions = {
    timeoutIntervalInMs : options.timeoutIntervalInMs,
    clientRequestTimeoutInMs : options.clientRequestTimeoutInMs,
    accessConditions : options.accessConditions
  };
  
  if (options.skipSizeCheck) {
    this._getFileToStream(share, directory, file, writeStream, options, callback);
  } else {
    var self = this;
    this.getFileProperties(share, directory, file, propertiesRequestOptions, function (error, properties) {
      if (error) {
        callback(error);
      } else {
        var size;
        if (options.rangeStart) {
          var endOffset = properties.contentLength - 1;
          var end = options.rangeEnd ? Math.min(options.rangeEnd, endOffset) : endOffset;
          size = end - options.rangeStart + 1;
        } else {
          size = properties.contentLength;
        }
        options.speedSummary.totalSize = size;
        
        if (size > self.singleFileThresholdInBytes) {
          azureutil.setObjectInnerPropertyValue(options, ['contentSettings', 'contentMD5'], azureutil.tryGetValueChain(properties, ['contentSettings', 'contentMD5'], null));
          self._getFileToRangeStream(share, directory, file, writeStream, options, callback);
        } else {
          self._getFileToStream(share, directory, file, writeStream, options, callback);
        }
      }
    });
  }
  
  return options.speedSummary;
};
 
/**
* Lists file ranges. Lists all of the ranges by default, or only the ranges over a specific range of bytes if rangeStart and rangeEnd are specified.
*
* @this {FileService}
* @param {string}             share                                       The share name.
* @param {string}             directory                                   The directory name. Use '' to refer to the base directory.
* @param {string}             file                                        The file name. File names may not start or end with the delimiter '/'.
* @param {object}             [options]                                   The request options.
* @param {int}                [options.rangeStart]                        The range start.
* @param {int}                [options.rangeEnd]                          The range end.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link FileResult}` will contain
*                                                                         the range information.
*                                                                         `response` will contain information related to this operation.
*/
FileService.prototype.listRanges = function (share, directory, file, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('listRanges', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.string(file, 'file');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var resourceName = createResourceName(share, directory, file);
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.get(resourceName)
    .withQueryOption(QueryStringConstants.COMP, 'rangelist');
 
  FileResult.setHeaders(webResource, options);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.ranges = null;
    if (!responseObject.error) {
      responseObject.ranges = [];
 
      var ranges = [];
      if (responseObject.response.body.Ranges.Range) {
        ranges = responseObject.response.body.Ranges.Range;
 
        if (!_.isArray(ranges)) {
          ranges = [ ranges ];
        }
      }
 
      ranges.forEach(function (fileRange) {
        var range = {
          start: parseInt(fileRange.Start, 10),
          end: parseInt(fileRange.End, 10)
        };
 
        responseObject.ranges.push(range);
      });
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.ranges, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Clears a range. Clears all of the ranges by default, or only the ranges over a specific range of bytes if rangeStart and rangeEnd are specified.
*
* @this {FileService}
* @param {string}             share                                       The share name.
* @param {string}             directory                                   The directory name. Use '' to refer to the base directory.
* @param {string}             file                                        The file name. File names may not start or end with the delimiter '/'.
* @param {int}                rangeStart                                  The range start.
* @param {int}                rangeEnd                                    The range end.
* @param {object}             [options]                                   The request options.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link FileResult}` will contain
*                                                                         the directory information.
*                                                                        `response` will contain information related to this operation.
*/
FileService.prototype.clearRange = function (share, directory, file, rangeStart, rangeEnd, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('clearRange', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.string(file, 'file');
    v.shareNameIsValid(share);
    v.value(rangeStart);
    v.value(rangeEnd);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var request = this._updateFilesImpl(share, directory, file, rangeStart, rangeEnd, FileConstants.RangeWriteOptions.CLEAR, options);
 
  var processResponseCallback = function(responseObject, next) {
    responseObject.fileResult = null;
    if (!responseObject.error) {
      responseObject.fileResult = new FileResult(share, directory, file);
      responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
    
    var finalCallback = function(returnObject) {
      callback(returnObject.error, returnObject.fileResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(request, null, options, processResponseCallback);
};
 
/**
* Updates a range from a stream.
*
* @this {FileService}
* @param {string}             share                                       The share name.
* @param {string}             directory                                   The directory name. Use '' to refer to the base directory.
* @param {string}             file                                        The file name. File names may not start or end with the delimiter '/'.
* @param {Stream}             readStream                                  The read stream.
* @param {int}                rangeStart                                  The range start.
* @param {int}                rangeEnd                                    The range end.
* @param {object}             [options]                                   The request options.
* @param {bool}               [options.useTransactionalMD5]               Calculate and send/validate content MD5 for transactions.
* @param {string}             [options.transactionalContentMD5]           An optional hash value used to ensure transactional integrity for the page. 
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link FileResult}` will contain
*                                                                         the file information.
*                                                                         `response` will contain information related to this operation.
*/
FileService.prototype.createRangesFromStream = function (share, directory, file, readStream, rangeStart, rangeEnd, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('createRangesFromStream', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.string(file, 'file');
    v.object(readStream, 'readStream');
    v.shareNameIsValid(share);
    v.value(rangeStart);
    v.value(rangeEnd);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var requiresContentMD5 = azureutil.objectIsNull(options.transactionalContentMD5) && options.useTransactionalMD5 === true;
 
  var length = (rangeEnd - rangeStart) + 1;
  if(length > FileConstants.MAX_UPDATE_FILE_SIZE) {
    throw new Error(SR.INVALID_FILE_RANGE_FOR_UPDATE);
  }
 
  var self = this;
  if (requiresContentMD5) {
    azureutil.calculateMD5(readStream, length, options, function(internalBuff, contentMD5) {
      options.transactionalContentMD5 = contentMD5;
      self._createRanges(share, directory, file, internalBuff, null /* stream */, rangeStart, rangeEnd, options, callback);
    });
  } else {
    self._createRanges(share, directory, file, null /* text */, readStream, rangeStart, rangeEnd, options, callback);
  }
};
 
/**
* Uploads a file from a text string. If the file already exists on the service, it will be overwritten.
*
* @this {FileService}
* @param {string}             share                                         The share name.
* @param {string}             directory                                     The directory name. Use '' to refer to the base directory.
* @param {string}             file                                          The file name. File names may not start or end with the delimiter '/'.
* @param {string|object}      text                                          The file text, as a string or in a Buffer.
* @param {object}             [options]                                     The request options.
* @param {SpeedSummary}       [options.speedSummary]                        The upload tracker objects;
* @param {bool}               [options.storeFileContentMD5]                 Specifies whether the file's ContentMD5 header should be set on uploads. 
*                                                                           The default value is false for files.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {object}             [options.contentSettings]                     The file's content settings.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the file. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the file.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The file service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The file's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The file's MD5 hash.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {FileService~FileToText}  callback                                 `error` will contain information
*                                                                           if an error occurs; otherwise `text` will contain the file contents,
*                                                                           and `[file]{@link FileResult}` will contain the file information.
*                                                                           `response` will contain information related to this operation.
*/
FileService.prototype.createFileFromText = function (share, directory, file, text, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('createFileFromText', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.string(file, 'file');
    v.exists(text, 'text');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
 
  var length = Buffer.isBuffer(text) ? text.length : Buffer.byteLength(text);
  if (length > FileConstants.MAX_UPDATE_FILE_SIZE) {
    throw new Error(SR.INVALID_FILE_LENGTH);
  }
 
  if(options.storeFileContentMD5 && azureutil.objectIsNull(azureutil.tryGetValueChain(options, ['contentSettings', 'contentMD5'], null))) {
     azureutil.setObjectInnerPropertyValue(options, ['contentSettings', 'contentMD5'], azureutil.getContentMd5(text));
  }
 
  var self = this;
  this.createFile(share, directory, file, length, options, function(error) {
    if(error) {
      callback(error);
    }
    else {
      self._createRanges(share, directory, file, text, null, 0, length - 1, options, callback);
    }
  });
};
 
/**
* Uploads a file to storage from a local file. If the file already exists on the service, it will be overwritten.
* (Not recommended for use in the JavaScript Client Library)
*
* @this {FileService}
* @param {string}             share                                         The share name.
* @param {string}             directory                                     The directory name. Use '' to refer to the base directory.
* @param {string}             file                                          The file name. File names may not start or end with the delimiter '/'.
* @param (string)             localFileName                                 The local path to the file to be uploaded.
* @param {object}             [options]                                     The request options.
* @param {SpeedSummary}       [options.speedSummary]                        The download tracker objects;
* @param {bool}               [options.storeFileContentMD5]                 Specifies whether the file's ContentMD5 header should be set on uploads. 
*                                                                           The default value is false for files.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {object}             [options.contentSettings]                     The file's content settings.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the file. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the file.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The file service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The file's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The file's MD5 hash.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      `error` will contain information if an error occurs; 
*                                                                           otherwise `[result]{@link FileResult}` will contain the file information.
*                                                                           `response` will contain information related to this operation.
* @return {SpeedSummary}
*/
FileService.prototype.createFileFromLocalFile = function (share, directory, file, localFileName, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('createFileFromLocalFile', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.string(file, 'file');
    v.string(localFileName, 'localFileName');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  options.speedSummary = options.speedSummary || new SpeedSummary(file);
 
  var self = this;
  fs.stat(localFileName, function(error, stat) {
    if (error) {
      callback(error);
    } else {
      self.createFile(share, directory, file, stat.size, options, function(error) {
        if(error) {
          callback(error);
        } else {
          var stream = new FileReadStream(localFileName, {calcContentMd5: options.storeFileContentMD5});
          self._createFileFromChunkStream(share, directory, file, stream, stat.size, options, callback);
        }
      });
    }
  });
 
  return options.speedSummary;
};
 
/**
* Uploads a file from a stream. If the file already exists on the service, it will be overwritten.
*
* @this {FileService}
* @param {string}             share                                         The share name.
* @param {string}             directory                                     The directory name. Use '' to refer to the base directory.
* @param {string}             file                                          The file name. File names may not start or end with the delimiter '/'. 
* @param (Stream)             stream                                        Stream to the data to store.
* @param {int}                streamLength                                  The length of the stream to upload.
* @param {object}             [options]                                     The request options.
* @param {SpeedSummary}       [options.speedSummary]                        The download tracker objects;
* @param {bool}               [options.storeFileContentMD5]                 Specifies whether the file's ContentMD5 header should be set on uploads. 
*                                                                           The default value is false for files.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {object}             [options.contentSettings]                     The file's content settings.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the file. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the file.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The file service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The file's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The file's MD5 hash.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      `error` will contain information if an error occurs; 
*                                                                           otherwise `[result]{@link FileResult}` will contain the file information.
*                                                                           `response` will contain information related to this operation.
* @return {SpeedSummary}
*/
FileService.prototype.createFileFromStream = function(share, directory, file, stream, streamLength, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('createFileFromStream', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.string(file, 'file');
    v.object(stream, 'stream');
    v.value(streamLength, 'streamLength');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  options.speedSummary = options.speedSummary || new SpeedSummary(file);
 
  stream.pause(); // Immediately pause the stream in order to compatible with Node v0.8
 
  var self = this;
  this.createFile(share, directory, file, streamLength, options, function(error) {
    if(error) {
      callback(error);
    } else {
      var chunkStream = new ChunkStreamWithStream(stream, {calcContentMd5: options.storeFileContentMD5});
      self._createFileFromChunkStream(share, directory, file, chunkStream, streamLength, options, callback);
    }
  });
 
  return options.speedSummary;
};
 
/**
* Provides a stream to write to a file. Assumes that the file exists. 
* If it does not, please create the file using createFile before calling this method or use createWriteStreamNewFile.
*
* @this {FileService}
* @param {string}             share                                         The share name.
* @param {string}             directory                                     The directory name. Use '' to refer to the base directory.
* @param {string}             file                                          The file name. File names may not start or end with the delimiter '/'.
* @param {object}             [options]                                     The request options.
* @param {SpeedSummary}       [options.speedSummary]                        The download tracker objects;
* @param {bool}               [options.storeFileContentMD5]                 Specifies whether the file's ContentMD5 header should be set on uploads. 
*                                                                           The default value is false for files.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {object}             [options.contentSettings]                     The file's content settings.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the file. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the file.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The file service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The file's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The file's MD5 hash.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      `error` will contain information if an error occurs; 
*                                                                           otherwise `[result]{@link FileResult}` will contain the file information.
*                                                                           `response` will contain information related to this operation.
* @return {Stream}
* @example
* var azure = require('azure-storage');
* var FileService = azure.createFileService();
* FileService.createFile(shareName, directoryName, fileName, 1024, function (err) {
*   // Pipe file to a file
*   var stream = fs.createReadStream(fileNameTarget).pipe(FileService.createWriteStreamToExistingFile(shareName, directoryName, fileName));
* });
*/
FileService.prototype.createWriteStreamToExistingFile = function (share, directory, file, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('createWriteStreamToExistingFile', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.string(file, 'file');
    v.shareNameIsValid(share);
  });
 
  var options = extend(true, {}, userOptions);
 
  var stream = new ChunkStream({calcContentMd5: options.storeFileContentMD5});
  this._createFileFromChunkStream(share, directory, file, stream, null, options, function (error, file, response) {
    if(error) {
      stream.emit('error', error);
    }
 
    if (callback) {
      callback(error, file, response);
    }
  });
 
  return stream;
};
 
/**
* Provides a stream to write to a file. Creates the file before writing data.
*
* @this {FileService}
* @param {string}             share                                         The share name.
* @param {string}             directory                                     The directory name. Use '' to refer to the base directory.
* @param {string}             file                                          The file name. File names may not start or end with the delimiter '/'.
* @param {string}             length                                        The file length.
* @param {object}             [options]                                     The request options.
* @param {SpeedSummary}       [options.speedSummary]                        The download tracker objects;
* @param {bool}               [options.storeFileContentMD5]                 Specifies whether the file's ContentMD5 header should be set on uploads. 
*                                                                           The default value is false for files.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {object}             [options.contentSettings]                     The file's content settings.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the file. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the file.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The file service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The file's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The file's MD5 hash.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {errorOrResult}      callback                                      `error` will contain information if an error occurs; 
*                                                                           otherwise `[result]{@link FileResult}` will contain the file information.
*                                                                           `response` will contain information related to this operation.
* @return {Stream}
* @example
* var azure = require('azure-storage');
* var FileService = azure.createFileService();
* var stream = fs.createReadStream(fileNameTarget).pipe(FileService.createWriteStreamToNewFile(shareName, directoryName, fileName));
*/
FileService.prototype.createWriteStreamToNewFile = function (share, directory, file, length, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('createWriteStreamToNewFile', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.string(file, 'file');
    v.value(length, 'length');
    v.shareNameIsValid(share);
  });
 
  var options = extend(true, {}, userOptions);
 
  var stream = new ChunkStream({calcContentMd5: options.storeFileContentMD5});
  stream.pause();
  
  var self = this;
  this.createFile(share, directory, file, length, options, function(error) {
    if(error) {
      stream.emit('error', error);
      callback(error);
    }
    else {
      stream.resume();
      self._createFileFromChunkStream(share, directory, file, stream, null, options, function (error, file, response) {
        if(error) {
          stream.emit('error', error);
        }
 
        if (callback) {
          callback(error, file, response);
        }
      });
    }
  });
  
  return stream;
};
 
/**
* Starts to copy a file to a destination within the storage account.
*
* @this {FileService}
* @param {string}             sourceUri                                 The source file or blob URI.
* @param {string}             targetShare                               The target share name.
* @param {string}             targetDirectory                           The target directory name.
* @param {string}             targetFile                                The target file name.
* @param {object}             [options]                                 The request options.
* @param {object}             [options.metadata]                        The target file metadata key/value pairs.
* @param {AccessConditions}   [options.accessConditions]                The access conditions.
* @param {AccessConditions}   [options.sourceAccessConditions]          The source access conditions.
* @param {LocationMode}       [options.locationMode]                    Specifies the location mode used to decide which location the request should be sent to. 
*                                                                       Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]             The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]        The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]        The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                       The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                       execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                 A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]               Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                       The default value is false.
* @param {errorOrResult}      callback                                  `error` will contain information if an error occurs; 
*                                                                       otherwise `[result]{@link FileResult}` will contain the file information.
*                                                                       `response` will contain information related to this operation.
*/
FileService.prototype.startCopyFile = function (sourceUri, targetShare, targetDirectory, targetFile, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  
  validate.validateArgs('startCopyFile', function (v) {
    v.string(targetShare, 'targetShare');
    v.stringAllowEmpty(targetDirectory, 'targetDirectory');
    v.string(targetFile, 'targetFile');
    v.shareNameIsValid(targetShare);
    v.callback(callback);
  });
  
  var targetResourceName = createResourceName(targetShare, targetDirectory, targetFile);
  
  var options = extend(true, {}, userOptions);
  
  var webResource = WebResource.put(targetResourceName)
    .withHeader(HeaderConstants.COPY_SOURCE, sourceUri)
    .addOptionalMetadataHeaders(options.metadata);
  
  var processResponseCallback = function (responseObject, next) {
    responseObject.fileResult = null;
    if (!responseObject.error) {
      responseObject.fileResult = new FileResult(targetShare, targetDirectory, targetFile);
      responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers, true);
      
      if (options.metadata) {
        responseObject.fileResult.metadata = options.metadata;
      }
    }
    
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.fileResult, returnObject.response);
    };
    
    next(responseObject, finalCallback);
  };
  
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Abort a file copy operation.
*
* @this {FileService}
* @param {string}             share                                     The destination share name.
* @param {string}             directory                                 The destination directory name.
* @param {string}             file                                      The destination file name.
* @param {string}             copyId                                    The copy operation identifier.
* @param {object}             [options]                                 The request options.
* @param {LocationMode}       [options.locationMode]                    Specifies the location mode used to decide which location the request should be sent to. 
*                                                                       Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]             The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]        The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]        The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                       The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                       execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                 A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]               Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                       The default value is false.
* @param {errorOrResult}      callback                                  `error` will contain information if an error occurs; 
*                                                                       otherwise `[result]{@link FileResult}` will contain the file information.
*                                                                       `response` will contain information related to this operation.
*/
FileService.prototype.abortCopyFile = function (share, directory, file, copyId, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
  
  validate.validateArgs('abortCopyFile', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.string(file, 'file');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
  
  var resourceName = createResourceName(share, directory, file);
  
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.put(resourceName)
    .withQueryOption(QueryStringConstants.COPY_ID, copyId)
    .withQueryOption(QueryStringConstants.COMP, 'copy')
    .withHeader(HeaderConstants.COPY_ACTION, 'abort');
  
  var processResponseCallback = function (responseObject, next) {
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.response);
    };
    
    next(responseObject, finalCallback);
  };
  
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
// Internal Methods
 
/**
* Updates a file from text.
* @ignore
*
* @this {FileService}
* @param {string}             share                                       The share name.
* @param {string}             directory                                   The directory name. Use '' to refer to the base directory.
* @param {string}             file                                        The file name. File names may not start or end with the delimiter '/'.
* @param {string}             text                                        The text string.
* @param {Stream}             readStream                                  The read stream.
* @param {int}                rangeStart                                  The range start.
* @param {int}                rangeEnd                                    The range end.
* @param {object}             [options]                                   The request options.
* @param {bool}               [options.useTransactionalMD5]               Calculate and send/validate content MD5 for transactions.
* @param {bool}               [options.transactionalContentMD5]           An MD5 hash of the content. This hash is used to verify the integrity of the data during transport.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {Function(error, file, response)}  callback                      `error` will contain information
*                                                                         if an error occurs; otherwise `file` will contain
*                                                                         the file information.
*                                                                         `response` will contain information related to this operation.
*/
FileService.prototype._createRanges = function (share, directory, file, text, readStream, rangeStart, rangeEnd, options, callback) {
var request = this._updateFilesImpl(share, directory, file, rangeStart, rangeEnd, FileConstants.RangeWriteOptions.UPDATE, options);
 
  // At this point, we have already validated that the range is less than 4MB. Therefore, we just need to calculate the contentMD5 if required.
  if(!azureutil.objectIsNull(text) && azureutil.objectIsNull(options.transactionalContentMD5) && options.useTransactionalMD5 === true) {
    request.withHeader(HeaderConstants.CONTENT_MD5, azureutil.getContentMd5(text));
  }
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.fileResult = null;
    if (!responseObject.error) {
      responseObject.fileResult = new FileResult(share, directory, file);
      responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.fileResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  if(!azureutil.objectIsNull(text)) {
    this.performRequest(request, text, options, processResponseCallback);
  } else {
    this.performRequestOutputStream(request, readStream, options, processResponseCallback);
  }
};
 
/**
* Uploads a file from a stream.
* @ignore
*
* @this {FileService}
* @param {string}             share                                         The share name.
* @param {string}             directory                                     The directory name. Use '' to refer to the base directory.
* @param {string}             file                                          The file name. File names may not start or end with the delimiter '/'.
* @param (Stream)             stream                                        Stream to the data to store.
* @param {int}                streamLength                                  The length of the stream to upload.
* @param {object|function}    [options]                                     The request options.
* @param {SpeedSummary}       [options.speedSummary]                        The download tracker objects;
* @param {int}                [options.parallelOperationThreadCount]        Parallel operation thread count.
* @param {bool}               [options.useTransactionalMD5]                 Calculate and send/validate content MD5 for transactions.
* @param {bool}               [options.storeFileContentMD5]                 Specifies whether the file's ContentMD5 header should be set on uploads.
* @param {string}             [options.contentSettings.contentType]         The MIME content type of the file. The default type is application/octet-stream.
* @param {string}             [options.contentSettings.contentEncoding]     The content encodings that have been applied to the file.
* @param {string}             [options.contentSettings.contentLanguage]     The natural languages used by this resource.
* @param {string}             [options.contentSettings.cacheControl]        The file service stores this value but does not use or modify it.
* @param {string}             [options.contentSettings.contentDisposition]  The file's content disposition.
* @param {string}             [options.contentSettings.contentMD5]          The MD5 hash of the file content.
* @param {object}             [options.metadata]                            The metadata key/value pairs.
* @param {LocationMode}       [options.locationMode]                        Specifies the location mode used to decide which location the request should be sent to. 
*                                                                           Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                 The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]            The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]            The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                           The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                           execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                     A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                   Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                           The default value is false.
* @param {function(error, null)}  callback                                  The callback function.
* @return {SpeedSummary}
*/
FileService.prototype._createFileFromChunkStream = function(share, directory, file, chunkStream, streamLength, options, callback) {
  this.logger.debug(util.format('_createFileFromChunkStream for file %s', file));
 
  var apiName = '_createRanges';
  var sizeLimitation = FileConstants.DEFAULT_WRITE_SIZE_IN_BYTES;
  var originalContentMD5 = azureutil.tryGetValueChain(options, ['contentSettings', 'contentMD5'], null);
 
  this._setOperationExpiryTime(options);
 
  // initialize the speed summary
  var speedSummary = options.speedSummary || new SpeedSummary();
  speedSummary.totalSize = streamLength;
 
  var parallelOperationThreadCount = options.parallelOperationThreadCount || this.parallelOperationThreadCount;
 
  // initialize chunk allocator
  var allocator = new ChunkAllocator(sizeLimitation, parallelOperationThreadCount, { logger: this.logger });
 
  // if this is a FileReadStream, set the allocator on that stream
  if (chunkStream._stream && chunkStream._stream.setMemoryAllocator) {
    chunkStream._stream.setMemoryAllocator(allocator);
  }
 
  // initialize batch operations
  var batchOperations = new BatchOperation(apiName, { logger : this.logger });
  batchOperations.setConcurrency(parallelOperationThreadCount);
 
  // initialize options
  var rangeOptions = {
    timeoutIntervalInMs: options.timeoutIntervalInMs,
    clientRequestTimeoutInMs: options.clientRequestTimeoutInMs,
    operationExpiryTime: options.operationExpiryTime
  };
 
  var self = this;
  chunkStream.on('data', function (data, range) {
    var operation = null;
    var full = false;
    var autoIncrement = speedSummary.getAutoIncrementFunction(data.length);
 
    if(data.length > sizeLimitation) {
      throw new Error(util.format(SR.EXCEEDED_SIZE_LIMITATION, sizeLimitation, data.length));
    }
 
    if (options.useTransactionalMD5) {
      //calculate content md5 for the current uploading block data
      var contentMD5 = azureutil.getContentMd5(data);
      rangeOptions.transactionalContentMD5 = contentMD5;
    }
 
    if (azureutil.isBufferAllZero(data)) {
      self.logger.debug(util.format('Skip upload data from %s bytes to %s bytes to file %s', range.start, range.end, file));
      speedSummary.increment(data.length);
    } else {
      operation = new BatchOperation.RestOperation(self, apiName, share, directory, file, data, null, range.start, range.end, rangeOptions, function (error) {
        if(!error) {
          autoIncrement();
        }
        allocator.releaseBuffer(data);
        data = null;
      });
    }
 
    if (operation) {
      full = batchOperations.addOperation(operation);
      operation = null;
 
      if(full) {
        self.logger.debug('file stream paused');
        chunkStream.pause();
      }
    }
  });
 
  chunkStream.on('end', function () {
    self.logger.debug(util.format('File read stream ended for file %s', file));
    batchOperations.enableComplete();
  });
 
  batchOperations.on('drain', function () {
    self.logger.debug('File stream resume');
    chunkStream.resume();
  });
 
  batchOperations.on('end', function (error) {
    self.logger.debug('batch operations commited');
 
    if (error) {
      callback(error);
      return;
    }
 
    if (originalContentMD5) {
      options.contentSettings.contentMD5 = originalContentMD5;
    } else if (options.storeFileContentMD5) {
      azureutil.setObjectInnerPropertyValue(options, ['contentSettings', 'contentMD5'], chunkStream.getContentMd5('base64'));
    }
 
    // upload file completely
    var fileProperties = extend(false, options.contentSettings, { contentLength: options.streamLength });
    self.setFileProperties(share, directory, file, fileProperties, function (error, file, response) {
      chunkStream.finish();
      callback(error, file, response);
    });
  });
 
  return speedSummary;
};
 
/**
* Downloads a file into a stream.
* @ignore
*
* @this {FileService}
* @param {string}             share                                       The share name.
* @param {string}             directory                                   The directory name. Use '' to refer to the base directory.
* @param {string}             file                                        The file name. File names may not start or end with the delimiter '/'.
* @param {Stream}             writeStream                                 The write stream.
* @param {object}             [options]                                   The request options.
* @param {string}             [options.rangeStart]                        Return only the bytes of the file in the specified range.
* @param {string}             [options.rangeEnd]                          Return only the bytes of the file in the specified range. 
* @param {boolean}            [options.useTransactionalMD5]               When set to true, Calculate and send/validate content MD5 for transactions.
* @param {boolean}            [options.disableContentMD5Validation]       When set to true, MD5 validation will be disabled when downloading files.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information if an error occurs; 
*                                                                         otherwise `result` will contain the file information.
*                                                                         `response` will contain information related to this operation.
*
* @return {SpeedSummary}
*/
FileService.prototype._getFileToStream = function (share, directory, file, writeStream, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('_getFileToStream', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.string(file, 'file');
    v.object(writeStream, 'writeStream');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var resourceName = createResourceName(share, directory, file);
  var webResource = WebResource.get(resourceName).withRawResponse();
 
  FileResult.setHeaders(webResource, options);
  this._setRangeContentMD5Header(webResource, options);
 
  var self = this;
  var processResponseCallback = function (responseObject, next) {
    responseObject.fileResult = null;
 
    if (!responseObject.error) {
      responseObject.fileResult = new FileResult(share, directory, file);
      responseObject.fileResult.metadata = self.parseMetadataHeaders(responseObject.response.headers);
      responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers, true);
 
      self._validateLengthAndMD5(options, responseObject);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.fileResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequestInputStream(webResource, null, writeStream, options, processResponseCallback);
};
 
/**
* Downloads a file into a range stream.
* @ignore
*
* @this {FileService}
* @param {string}             share                                       The share name.
* @param {string}             directory                                   The directory name. Use '' to refer to the base directory.
* @param {string}             file                                        The file name. File names may not start or end with the delimiter '/'.
* @param {Stream}             writeStream                                 The write stream.
* @param {object}             [options]                                   The request options.
* @param {int}                [options.parallelOperationThreadCount]      Parallel operation thread count.
* @param {string}             [options.rangeStart]                        Return only the bytes of the file in the specified range.
* @param {string}             [options.rangeEnd]                          Return only the bytes of the file in the specified range. 
* @param {boolean}            [options.useTransactionalMD5]               When set to true, Calculate and send/validate content MD5 for transactions.
* @param {boolean}            [options.disableContentMD5Validation]       When set to true, MD5 validation will be disabled when downloading files.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information if an error occurs; 
*                                                                         otherwise `result` will contain the file information.
*                                                                         `response` will contain information related to this operation.
*
* @return {SpeedSummary}
*/
FileService.prototype._getFileToRangeStream = function (share, directory, file, writeStream, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('_getFileToRangeStream', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.string(file, 'file');
    v.object(writeStream, 'writeStream');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var speedSummary = userOptions.speedSummary || new SpeedSummary(file);
  var parallelOperationThreadCount = userOptions.parallelOperationThreadCount || this.parallelOperationThreadCount;
  var batchOperations = new BatchOperation('getfile', { callbackInOrder: true, logger : this.logger });
  batchOperations.setConcurrency(parallelOperationThreadCount);
 
  var rangeStream = new FileRangeStream(this, share, directory, file, userOptions);
 
  var self = this;
  var checkMD5sum = !userOptions.disableContentMD5Validation;
  var md5Hash = null;
  if (checkMD5sum) {
    md5Hash = new Md5Wrapper().createMd5Hash();
  }
 
  var savedFileResult = null;
  var savedFileResponse = null;
 
  rangeStream.on('range', function (range) {
    if (!speedSummary.totalSize) {
      speedSummary.totalSize = rangeStream.rangeSize;
    }
 
    var requestOptions = {
      rangeStart : range.start,
      rangeEnd : range.end,
      responseEncoding : null //Use Buffer to store the response data
    };
 
    var rangeSize = range.size;
    requestOptions.timeoutIntervalInMs = userOptions.timeoutIntervalInMs;
    requestOptions.clientRequestTimeoutInMs = userOptions.clientRequestTimeoutInMs;
    requestOptions.useTransactionalMD5 = userOptions.useTransactionalMD5;
 
    if (range.dataSize === 0) {
      var autoIncrement = speedSummary.getAutoIncrementFunction(rangeSize);
      //No operation to do and only wait for write zero to file in callback
      var writeZeroOperation = new BatchOperation.CommonOperation(BatchOperation.noOperation, function (error) {
        if (error) return;
        var bufferAvailable = azureutil.writeZerosToStream(writeStream, rangeSize, md5Hash, autoIncrement);
        //There is no need to pause the rangestream since we can perform http request and write disk at the same time
        self.logger.debug(util.format('Write %s bytes Zero from %s to %s', rangeSize, range.start, range.end));
        if (!bufferAvailable) {
          self.logger.debug('Write stream is full and pause batch operation');
          batchOperations.pause();
        }
      });
      batchOperations.addOperation(writeZeroOperation);
      return;
    }
      
    if (range.start > range.end) {
      return;
    }
      
    var operation = new BatchOperation.RestOperation(self, 'getFileToText', share, directory, file, requestOptions, function (error, content, fileResult, response) {
      if (!error) {
        if (rangeSize !== content.length) {
          self.logger.warn(util.format('Request %s bytes, but server returns %s bytes', rangeSize, content.length));
        }
        //Save one of the succeeded callback parameters and use them at the final callback
        if (!savedFileResult) {
          savedFileResult = fileResult;
        }
        if (!savedFileResponse) {
          savedFileResponse = response;
        }
        var autoIncrement = speedSummary.getAutoIncrementFunction(content.length);
        var bufferAvailable = writeStream.write(content, autoIncrement);
        if (!bufferAvailable) {
          self.logger.debug('Write stream is full and pause batch operation');
          batchOperations.pause();
        }
        if (md5Hash) {
          md5Hash.update(content);
        }
        content = null;
      }
    });
 
    var full = batchOperations.addOperation(operation);
    if (full) {
      self.logger.debug('Pause range stream');
      rangeStream.pause();
    }    
  });
  
  rangeStream.on('end', function () {
    self.logger.debug('Range stream has ended.');
    batchOperations.enableComplete();
  });
  
  batchOperations.on('drain', function () {
    self.logger.debug('Resume range stream');
    rangeStream.resume();
  });
  
  writeStream.on('drain', function () {
    self.logger.debug('Resume batch operations');
    batchOperations.resume();
  });
  
  batchOperations.on('end', function (error) {
    self.logger.debug('Download completed!');
    if (error) {
      callback(error);
    } else {
      writeStream.end(function () {
        self.logger.debug('Write stream has ended');
        if (writeStream.close) {
          writeStream.close();
        }
        if (!savedFileResult) {
          savedFileResult = {};
        }
        azureutil.setObjectInnerPropertyValue(savedFileResult, ['contentSettings', 'contentMD5'], azureutil.tryGetValueChain(userOptions, ['contentSettings', 'contentMD5'], null));
        savedFileResult.clientSideContentMD5 = null;
        if (md5Hash) {
          savedFileResult.clientSideContentMD5 = md5Hash.digest('base64');
        }
        callback(error, savedFileResult, savedFileResponse);
      });
    }
  });
  
  var listOptions = {
    timeoutIntervalInMs : userOptions.timeoutIntervalInMs,
    clientRequestTimeoutInMs : userOptions.clientRequestTimeoutInMs,
  };
  
  rangeStream.list(listOptions);
  return speedSummary;
};
 
/**
* @ignore
*/
FileService.prototype._setRangeContentMD5Header = function (webResource, options) {
  if(!azureutil.objectIsNull(options.rangeStart) && options.useTransactionalMD5) {
    if(azureutil.objectIsNull(options.rangeEnd)) {
      throw new ArgumentNullError(util.format(SR.ARGUMENT_NULL_OR_EMPTY, options.rangeEndHeader));
    }
 
    var size = parseInt(options.rangeEnd, 10) - parseInt(options.rangeStart, 10) + 1;
    if (size > FileConstants.MAX_RANGE_GET_SIZE_WITH_MD5) {
      throw new Error(SR.INVALID_RANGE_FOR_MD5);
    } else {
      webResource.withHeader(HeaderConstants.RANGE_GET_CONTENT_MD5, 'true');
    }
  }
};
 
/**
* @ignore
*/
FileService.prototype._updateFilesImpl = function (share, directory, file, rangeStart, rangeEnd, writeMethod, options) {
  var resourceName = createResourceName(share, directory, file);
  var webResource = WebResource.put(resourceName)
    .withQueryOption(QueryStringConstants.COMP, 'range')
    .withHeader(HeaderConstants.CONTENT_TYPE, 'application/octet-stream')
    .withHeader(HeaderConstants.FILE_WRITE, writeMethod);
 
  options.rangeStart = rangeStart;
  options.rangeEnd = rangeEnd;
 
  FileResult.setHeaders(webResource, options); 
 
  if(writeMethod === FileConstants.RangeWriteOptions.UPDATE) {
    var size = (rangeEnd - rangeStart) + 1;
    webResource.withHeader(HeaderConstants.CONTENT_LENGTH, size);
  } else {
    webResource.withHeader(HeaderConstants.CONTENT_LENGTH, 0);
  }
 
  return webResource;
};
 
/**
* @ignore
*/
FileService.prototype._validateLengthAndMD5 = function (options, responseObject) {
  var storedMD5 = responseObject.response.headers[Constants.HeaderConstants.CONTENT_MD5];
  var contentLength;
 
  if (!azureutil.objectIsNull(responseObject.response.headers[Constants.HeaderConstants.CONTENT_LENGTH])) {
    contentLength = parseInt(responseObject.response.headers[Constants.HeaderConstants.CONTENT_LENGTH], 10);
  }
 
  // If the user has not specified this option, the default value should be false.
  if(azureutil.objectIsNull(options.disableContentMD5Validation)) {
    options.disableContentMD5Validation = false;
  }
 
  // None of the below cases should be retried. So set the error in every case so the retry policy filter handle knows that it shouldn't be retried.
  if (options.disableContentMD5Validation === false && options.useTransactionalMD5 === true && azureutil.objectIsNull(storedMD5)) {
    responseObject.error = new Error(SR.MD5_NOT_PRESENT_ERROR);
    responseObject.retryable = false;
  }
 
  // Validate length and if required, MD5.
  // If getFileToText called this method, then the responseObject.length and responseObject.contentMD5 are not set. Calculate them first using responseObject.response.body and then validate.
  if(azureutil.objectIsNull(responseObject.length)) {
    if (typeof responseObject.response.body == 'string') {
      responseObject.length = Buffer.byteLength(responseObject.response.body);
    } else if (Buffer.isBuffer(responseObject.response.body)) {
      responseObject.length = responseObject.response.body.length;
    }
  }
 
  if(!azureutil.objectIsNull(contentLength) && responseObject.length !== contentLength) {
    responseObject.error = new Error(SR.CONTENT_LENGTH_MISMATCH);
    responseObject.retryable = false;
  }
 
  if(options.disableContentMD5Validation === false && azureutil.objectIsNull(responseObject.contentMD5)) {
    responseObject.contentMD5 = azureutil.getContentMd5(responseObject.response.body);
  }
 
  if (options.disableContentMD5Validation === false && !azureutil.objectIsNull(storedMD5) && storedMD5 !== responseObject.contentMD5) {
    responseObject.error = new Error(util.format(SR.HASH_MISMATCH, storedMD5, responseObject.contentMD5));
    responseObject.retryable = false;
  }
};
 
/**
* Checks whether or not a file exists on the service.
* @ignore
*
* @this {FileService}
* @param {string}             share                                             The share name.
* @param {string}             directory                                         The directory name. Use '' to refer to the base directory.
* @param {string}             file                                              The file name. File names may not start or end with the delimiter '/'.
* @param {string}             primaryOnly                                       If true, the request will be executed against the primary storage location.
* @param {object}             [options]                                         The request options.
* @param {LocationMode}       [options.locationMode]                            Specifies the location mode used to decide which location the request should be sent to. 
*                                                                               Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                     The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]                The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]                The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                               The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                               execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                         A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                       Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                               The default value is false.
* @param {Function(error, result, response)}  callback                          `error` will contain information
*                                                                               if an error occurs; otherwise `result` will contain
*                                                                               the file information including the `exists` boolean member.
*                                                                               `response` will contain information related to this operation.
*/
FileService.prototype._doesFileExist = function (share, directory, file, primaryOnly, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('FileExists', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.string(file, 'file');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
 
  var resourceName = createResourceName(share, directory, file);
  var webResource = WebResource.head(resourceName);
 
  /*if(primaryOnly === false) {
    options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY;
  }*/
  
  var processResponseCallback = function (responseObject, next) {
    responseObject.fileResult = new FileResult(share, directory, file);
    if (!responseObject.error) {
      responseObject.fileResult.exists = true;
      responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers);
      
    } else if (responseObject.error && responseObject.error.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound) {
      responseObject.error = null;
      responseObject.fileResult.exists = false;
      responseObject.response.isSuccessful = true;
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.fileResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Checks whether or not a directory exists on the service.
* @ignore
*
* @this {FileService}
* @param {string}             share                                             The share name.
* @param {string}             directory                                         The directory name. Use '' to refer to the base directory.
* @param {string}             primaryOnly                                       If true, the request will be executed against the primary storage location.
* @param {object}             [options]                                         The request options.
* @param {LocationMode}       [options.locationMode]                            Specifies the location mode used to decide which location the request should be sent to. 
*                                                                               Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                     The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]                The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]                The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                               The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                               execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                         A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                       Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                               The default value is false.
* @param {Function(error, result, response)}  callback                          `error` will contain information
*                                                                               if an error occurs; otherwise `result` will contain
*                                                                               the directory information including `exists` boolean member. 
*                                                                               `response` will contain information related to this operation.
*/
FileService.prototype._doesDirectoryExist = function (share, directory, primaryOnly, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('directoryExists', function (v) {
    v.string(share, 'share');
    v.stringAllowEmpty(directory, 'directory');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.head(createResourceName(share, directory))
    .withQueryOption(QueryStringConstants.RESTYPE, 'directory');
 
  /*if(primaryOnly === false) {
    options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY;
  }*/
    
  var self = this;
  var processResponseCallback = function(responseObject, next){
    responseObject.directoryResult = new DirectoryResult(directory);
    responseObject.directoryResult.exists = false;
    
    if (!responseObject.error) {
      responseObject.directoryResult.exists = true;
      responseObject.directoryResult.metadata = self.parseMetadataHeaders(responseObject.response.headers);
      responseObject.directoryResult.getPropertiesFromHeaders(responseObject.response.headers);
      
    } else if (responseObject.error && responseObject.error.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound) {
      responseObject.error = null;
      responseObject.response.isSuccessful = true;
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.directoryResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Checks whether or not a share exists on the service.
* @ignore
*
* @this {FileService}
* @param {string}             share                                   The share name.
* @param {string}             primaryOnly                             If true, the request will be executed against the primary storage location.
* @param {object}             [options]                               The request options.
* @param {LocationMode}       [options.locationMode]                  Specifies the location mode used to decide which location the request should be sent to. 
*                                                                     Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]           The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]      The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]      The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                     The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                     execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]               A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]             Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                     The default value is false.
* @param {Function(error, result, response)}      callback            `error` will contain information
*                                                                     if an error occurs; otherwise `result` will contain
*                                                                     the share information including `exists` boolean member.
*                                                                     `response` will contain information related to this operation.
*/
FileService.prototype._doesShareExist = function (share, primaryOnly, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('shareExists', function (v) {
    v.string(share, 'share');
    v.shareNameIsValid(share);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.head(share)
    .withQueryOption(QueryStringConstants.RESTYPE, 'share');
 
  /*if(primaryOnly === false) {
    options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY;
  }*/
  
  var processResponseCallback = function(responseObject, next){
    responseObject.shareResult = new ShareResult(share);
    responseObject.shareResult.exists = false;
    
    if (!responseObject.error) {
      responseObject.shareResult.exists = true;
      responseObject.shareResult.getPropertiesFromHeaders(responseObject.response.headers);
      
    } else if (responseObject.error && responseObject.error.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound) {
      responseObject.error = null;
      responseObject.response.isSuccessful = true;
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.shareResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* The callback for {FileService~getFileToText}.
* @typedef {function} FileService~FileToText
* @param {object} error      If an error occurs, the error information.
* @param {string} text       The text returned from the file.
* @param {object} file       Information about the file.
* @param {object} response   Information related to this operation.
*/
 
FileService.SpeedSummary = SpeedSummary;
 
module.exports = FileService;
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/file/fileutilities.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/file/fileutilities.js

Statements: 100% (3 / 3)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (3 / 3)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63                                  1           1                                                                           1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Expose 'FileUtilities'.
exports = module.exports;
 
/**
* Defines constants, enums, and utility functions for use with the File service.
* @namespace FileUtilities
*/
var FileUtilities = {
  /**
  * Permission types
  *
  * @const
  * @enum {string}
  */
  SharedAccessPermissions: {
    READ: 'r',
    CREATE: 'c',
    WRITE: 'w',
    DELETE: 'd',
    LIST: 'l'
  },
 
  /**
  * Listing details.
  *
  * @const
  * @enum {string}
  */
  ListingDetails: {
    METADATA: 'metadata'
  },
 
  /**
  * File and share public access types.
  *
  * @const
  * @enum {string}
  */
  SharePublicAccessType: {
    OFF: null,
    SHARE: 'share',
    FILE: 'file'
  }
};
 
module.exports = FileUtilities;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/file/internal/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/file/internal/

Statements: 33.33% (6 / 18)      Branches: 0% (0 / 4)      Functions: 0% (0 / 1)      Lines: 33.33% (6 / 18)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/lib/services/file/internal/
File Statements Branches Functions Lines
filerangestream.js 33.33% (6 / 18) 0% (0 / 4) 0% (0 / 1) 33.33% (6 / 18)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/file/internal/filerangestream.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/file/internal/filerangestream.js

Statements: 33.33% (6 / 18)      Branches: 0% (0 / 4)      Functions: 0% (0 / 1)      Lines: 33.33% (6 / 18)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48                                1 1 1         1                                       1   1    
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var util = require('util');
var RangeStream = require('./../../../common/streams/rangestream');
var Constants = require('./../../../common/util/constants');
 
/**
* File range stream
*/
function FileRangeStream(fileServiceClient, share, directory, file, options) {
  FileRangeStream['super_'].call(this, fileServiceClient, null, null, options);
    
  this._lengthHeader = Constants.HeaderConstants.FILE_CONTENT_LENGTH;
  if (options.minRangeSize) {
    this._minRangeSize = options.minRangeSize;
  } else {
    this._minRangeSize = Constants.FileConstants.MIN_WRITE_FILE_SIZE_IN_BYTES;
  }
  if (options.maxRangeSize) {
    this._maxRangeSize = options.maxRangeSize;
  } else {
    this._maxRangeSize = Constants.FileConstants.DEFAULT_WRITE_SIZE_IN_BYTES;
  }
  this._listFunc = fileServiceClient.listRanges;
  this._resourcePath.push(share);
  this._resourcePath.push(directory);
  this._resourcePath.push(file);
}
 
util.inherits(FileRangeStream, RangeStream);
 
module.exports = FileRangeStream;
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/file/models/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/file/models/

Statements: 23.58% (25 / 106)      Branches: 0% (0 / 40)      Functions: 0% (0 / 17)      Lines: 23.58% (25 / 106)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/lib/services/file/models/
File Statements Branches Functions Lines
directoryresult.js 35.71% (5 / 14) 0% (0 / 4) 0% (0 / 4) 35.71% (5 / 14)
fileresult.js 18.75% (12 / 64) 0% (0 / 24) 0% (0 / 9) 18.75% (12 / 64)
shareresult.js 28.57% (8 / 28) 0% (0 / 12) 0% (0 / 4) 28.57% (8 / 28)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/file/models/directoryresult.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/file/models/directoryresult.js

Statements: 35.71% (5 / 14)      Branches: 0% (0 / 4)      Functions: 0% (0 / 4)      Lines: 35.71% (5 / 14)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57                                  1                               1       1       1                           1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var HeaderConstants = require('./../../../common/common').Constants.HeaderConstants;
 
/**
* Creates a new DirectoryResult object.
* @class
* The DirectoryResult class is used to store the directory information.
* 
 * @property  {string}                      name                                  The container name.
 * @property  {object}                      metadata                              The metadata key/value pair.
 * @property  {string}                      etag                                  The etag.
 * @property  {string}                      lastModified                          The date/time that the directory was last modified.
 * @property  {string}                      requestId                             The request id.
 * 
* @constructor
* @param {string} [name]                    The directory name.
*/
function DirectoryResult(name) {
  this.name = name;
}
 
DirectoryResult.parse = function (dirXml) {
  return new DirectoryResult(dirXml.Name);
};
 
DirectoryResult.prototype.getPropertiesFromHeaders = function (headers) {
  var self = this;
 
  var setDirectoryPropertyFromHeaders = function (directoryProperty, headerProperty) {
    if (!self[directoryProperty] && headers[headerProperty.toLowerCase()]) {
      self[directoryProperty] = headers[headerProperty.toLowerCase()];
    }
  };
 
  setDirectoryPropertyFromHeaders('etag', HeaderConstants.ETAG);
  setDirectoryPropertyFromHeaders('lastModified', HeaderConstants.LAST_MODIFIED);
  setDirectoryPropertyFromHeaders('requestId', HeaderConstants.REQUEST_ID);
};
 
module.exports = DirectoryResult;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/file/models/fileresult.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/file/models/fileresult.js

Statements: 18.75% (12 / 64)      Branches: 0% (0 / 24)      Functions: 0% (0 / 9)      Lines: 18.75% (12 / 64)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206                                  1   1 1 1 1                                                                         1           1                           1                                         1                                                                       1                                                               1                                                                       1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var _ = require('underscore');
 
var azureCommon = require('./../../../common/common');
var azureutil = azureCommon.util;
var Constants = azureCommon.Constants;
var HeaderConstants = Constants.HeaderConstants;
 
/**
* Creates a new FileResult object.
* @class
* The FileResult class is used to store the file information.
* 
 * @property  {string}                      share                                 The share name.
 * @property  {string}                      directory                             The directory name.
 * @property  {string}                      name                                  The file name.
 * @property  {object}                      metadata                              The metadata key/value pair.
 * @property  {string}                      etag                                  The etag.
 * @property  {string}                      lastModified                          The date/time that the file was last modified.
 * @property  {string}                      requestId                             The request id.
 * @property  {string}                      acceptRanges                          The accept ranges.
 * @property  {string}                      contentRange                          The content range
 * @property  {string}                      contentLength                         The size of the file in bytes.
 * @property  {object}                      contentSettings                       The content settings.
 * @property  {string}                      contentSettings.contentType           The content type.
 * @property  {string}                      contentSettings.contentEncoding       The content encoding.
 * @property  {string}                      contentSettings.contentLanguage       The content language.
 * @property  {string}                      contentSettings.cacheControl          The cache control.
 * @property  {string}                      contentSettings.contentDisposition    The content disposition.
 * @property  {string}                      contentSettings.contentMD5            The content MD5 hash.
 * @property  {object}                      copy                                  The copy information.
 * @property  {string}                      copy.id                               The copy id.
 * @property  {string}                      copy.status                           The copy status.
 * @property  {string}                      copy.completionTime                   The copy completion time. 
 * @property  {string}                      copy.statusDescription                The copy status description.
 * @property  {string}                      copy.progress                         The copy progress.
 * @property  {string}                      copy.source                           The copy source.
 * 
* @constructor
* @param {string} [share]      The share name.
* @param {string} [directory]  The directory name.
* @param {string} [name]       The file name.
*/
function FileResult(share, directory, name) {
  this.share = share;
  this.directory = directory;
  this.name = name;
}
 
FileResult.parse = function (entryXml) {
  var listResult = new FileResult();
  for (var propertyName in entryXml) {
    if (propertyName === 'Properties') {
      //  Lift out the properties onto the main object to keep consistent across all APIs like: getFileProperties
        azureutil.setPropertyValueFromXML(listResult, entryXml[propertyName], true);
    } else {
      listResult[propertyName.toLowerCase()] = entryXml[propertyName];
    }
  }
 
  return listResult;
};
 
var responseHeaders = {
  'acceptRanges': 'ACCEPT_RANGES',
  'contentLength': 'CONTENT_LENGTH',
  'contentRange': 'CONTENT_RANGE',
 
  'contentSettings.contentType': 'CONTENT_TYPE',
  'contentSettings.contentEncoding': 'CONTENT_ENCODING',
  'contentSettings.contentLanguage': 'CONTENT_LANGUAGE',
  'contentSettings.cacheControl': 'CACHE_CONTROL',
  'contentSettings.contentDisposition': 'CONTENT_DISPOSITION',
  'contentSettings.contentMD5': 'CONTENT_MD5',
  'contentSettings.fileContentMD5': 'FILE_CONTENT_MD5',
  
  'copy.id': 'COPY_ID',
  'copy.status': 'COPY_STATUS',
  'copy.source': 'COPY_SOURCE',
  'copy.progress': 'COPY_PROGRESS',
  'copy.completionTime': 'COPY_COMPLETION_TIME',
  'copy.statusDescription': 'COPY_STATUS_DESCRIPTION'
};
 
FileResult.prototype.getPropertiesFromHeaders = function (headers, content) {
  var self = this;
  
  var setFilePropertyFromHeaders = function (fileProperty, headerProperty) {
    if (!azureutil.tryGetValueChain(self, fileProperty.split('.'), null) && headers[headerProperty.toLowerCase()]) {
      azureutil.setObjectInnerPropertyValue(self, fileProperty.split('.'), headers[headerProperty.toLowerCase()]);
      
      if (fileProperty === 'copy.progress') {
        var info = azureutil.parseCopyProgress(self.copy.progress);
        self.copy.bytesCopied = parseInt(info.bytesCopied);
        self.copy.totalBytes = parseInt(info.totalBytes);
      }
    }
  };
   
  // For range get, 'x-ms-content-md5' indicate the overall MD5 of the file. Try to set the contentMD5 using this header if it presents
  setFilePropertyFromHeaders('contentSettings.contentMD5', HeaderConstants['FILE_CONTENT_MD5']); 
 
  setFilePropertyFromHeaders('etag', HeaderConstants.ETAG);
  setFilePropertyFromHeaders('lastModified', HeaderConstants.LAST_MODIFIED);
  setFilePropertyFromHeaders('requestId', HeaderConstants.REQUEST_ID);   
 
  if (content) {
     _.chain(responseHeaders).pairs().each(function (pair) {
      var property = pair[0];
      var header = HeaderConstants[pair[1]];
      setFilePropertyFromHeaders(property, header);
    });
 
   }
};
 
/**
* This method sets the HTTP headers and is used by all methods except setFileProperties and createFile. 
* Those methods will set the x-ms-* headers using setProperties.
*/
FileResult.setHeaders = function (webResource, options) {
  var setHeaderProperty = function (headerProperty, fileProperty) {
    var propertyValue = azureutil.tryGetValueChain(options, fileProperty.split('.'), null);
    if (propertyValue) {
      webResource.withHeader(headerProperty, propertyValue);
    }
  };
 
  if (options) {
    // Content-MD5
    setHeaderProperty(HeaderConstants.CONTENT_MD5, 'transactionalContentMD5');
 
    // Content-Length
    setHeaderProperty(HeaderConstants.CONTENT_LENGTH, 'contentLength');
 
    // Range
    if (!azureutil.objectIsNull(options.rangeStart)) {
      var range = 'bytes=' + options.rangeStart + '-';
 
      if (!azureutil.objectIsNull(options.rangeEnd)) {
        range += options.rangeEnd;
      }
 
      webResource.withHeader(HeaderConstants.STORAGE_RANGE, range);
    }   
  }
};
 
/**
* This method sets the x-ms-* headers and is used by setFileProperties and createFile. 
* All other methods will set the regular HTTP headers using setHeaders.
*/
FileResult.setProperties = function (webResource, options) {
  var setHeaderProperty = function (headerProperty, fileProperty) {
    var propertyValue = azureutil.tryGetValueChain(options, fileProperty.split('.'), null);
    if (propertyValue) {
      webResource.withHeader(headerProperty, propertyValue);
    }
  };
 
  if (options) {
    // Content-Length
    setHeaderProperty(HeaderConstants.FILE_CONTENT_LENGTH, 'contentLength');
    
    // Content-Type
    setHeaderProperty(HeaderConstants.FILE_CONTENT_TYPE, 'contentSettings.contentType');
 
    // Content-Encoding
    setHeaderProperty(HeaderConstants.FILE_CONTENT_ENCODING, 'contentSettings.contentEncoding');
 
    // Content-Language
    setHeaderProperty(HeaderConstants.FILE_CONTENT_LANGUAGE, 'contentSettings.contentLanguage');
 
    // Content-Disposition
    setHeaderProperty(HeaderConstants.FILE_CONTENT_DISPOSITION, 'contentSettings.contentDisposition');
 
    // Cache-Control
    setHeaderProperty(HeaderConstants.FILE_CACHE_CONTROL, 'contentSettings.cacheControl');
 
    // Content-MD5
    setHeaderProperty(HeaderConstants.FILE_CONTENT_MD5, 'contentSettings.contentMD5');
 
    if (options.metadata) {
      webResource.addOptionalMetadataHeaders(options.metadata);
    }
  }
};
 
module.exports = FileResult;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/file/models/shareresult.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/file/models/shareresult.js

Statements: 28.57% (8 / 28)      Branches: 0% (0 / 12)      Functions: 0% (0 / 4)      Lines: 28.57% (8 / 28)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85                                  1 1 1 1                                 1       1                                       1                                           1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var azureCommon = require('./../../../common/common');
var azureutil = azureCommon.util;
var Constants = azureCommon.Constants;
var HeaderConstants = Constants.HeaderConstants;
 
/**
* Creates a new ShareResult object.
* @class
* The ShareResult class is used to store the share information.
* 
 * @property  {string}                      name                                  The share name.
 * @property  {object}                      metadata                              The metadata key/value pair.
 * @property  {string}                      etag                                  The etag.
 * @property  {string}                      lastModified                          The date/time that the share was last modified.
 * @property  {string}                      requestId                             The request id.
 * @property  {string}                      quota                                 The share quota.
 * 
* @constructor
* @param {string} [name]                    The share name.
*/
function ShareResult(name) {
  this.name = name;
}
 
ShareResult.parse = function (shareXml, name) {
  var shareResult = new ShareResult(name);
  for (var propertyName in shareXml) {
    if (shareXml.hasOwnProperty(propertyName)) {
      if (propertyName === 'Properties') {
        //  Lift out the properties onto the main object to keep consistent across all APIs like: getShareProperties
        azureutil.setPropertyValueFromXML(shareResult, shareXml[propertyName], true);
      } else if (propertyName === 'Metadata' || propertyName === 'ShareStats') {
        var resultPropertyName = azureutil.normalizePropertyNameFromXML(propertyName);
        shareResult[resultPropertyName] = {};
        azureutil.setPropertyValueFromXML(shareResult[resultPropertyName], shareXml[propertyName], propertyName === 'ShareStats');
      } else {
        shareResult[propertyName.toLowerCase()] = shareXml[propertyName];
      }
    }
  }
 
  return shareResult;
};
 
ShareResult.prototype.getPropertiesFromHeaders = function (headers) {
  var self = this;
 
  var setSharePropertyFromHeaders = function (shareProperty, headerProperty) {
    if (!self[shareProperty] && headers[headerProperty.toLowerCase()]) {
      self[shareProperty] = headers[headerProperty.toLowerCase()];
    }
  };
 
  setSharePropertyFromHeaders('etag', HeaderConstants.ETAG);
  setSharePropertyFromHeaders('lastModified', HeaderConstants.LAST_MODIFIED);
  setSharePropertyFromHeaders('requestId', HeaderConstants.REQUEST_ID);
  setSharePropertyFromHeaders('quota', HeaderConstants.SHARE_QUOTA);
};
 
/**
* The share ACL settings.
* @typedef    {object}                ShareAclResult
* @extends    {ShareAclResult}
* @property   {Object.<string, AccessPolicy>}    signedIdentifiers   The container ACL settings. See `[AccessPolicy]{@link AccessPolicy}` for detailed information.
*/
 
module.exports = ShareResult;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/queue/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/queue/

Statements: 13.44% (70 / 521)      Branches: 0% (0 / 116)      Functions: 0% (0 / 118)      Lines: 14.55% (70 / 481)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/lib/services/queue/
File Statements Branches Functions Lines
queuemessageencoder.js 71.43% (20 / 28) 100% (0 / 0) 0% (0 / 12) 71.43% (20 / 28)
queueservice.js 9.59% (47 / 490) 0% (0 / 116) 0% (0 / 106) 10.44% (47 / 450)
queueutilities.js 100% (3 / 3) 100% (0 / 0) 100% (0 / 0) 100% (3 / 3)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/queue/queuemessageencoder.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/queue/queuemessageencoder.js

Statements: 71.43% (20 / 28)      Branches: 100% (0 / 0)      Functions: 0% (0 / 12)      Lines: 71.43% (20 / 28)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183                                    1                     1                 1                   1                             1   1                   1                       1                             1   1                   1                         1                             1   1                   1                               1               1 1 1 1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
 
var util = require('util');
 
/**
 * The interface for classes that represent a encoder which can be used to specify how the queue service encodes and decodes queue messages.
 * 
 * To specify how the queue service encodes and decodes queue messages, set `queueService.messageEncoder` to object of built-in encoder types
 * `[TextBase64QueueMessageEncoder]{@link TextBase64QueueMessageEncoder}`, `[BinaryBase64QueueMessageEncoder]{@link BinaryBase64QueueMessageEncoder}`, `[TextXmlQueueMessageEncoder]{@link TextXmlQueueMessageEncoder}`,
 * or custom implementation of the QueueMessageEncoder.
 * 
 * @class
 */
function QueueMessageEncoder() {
}
 
/**
 * Function to encode queue messages.
 * 
 * @param   {object}    [input]               The target to be encoded.
 * @return  {string}
 */
QueueMessageEncoder.prototype.encode = function(input){
  return input;
};
 
/**
 * Function to decode queue messages
 * 
 * @param   {string}    [textToBeDecoded]     The base64 string to be decoded.
 * @returns {any}
 */
QueueMessageEncoder.prototype.decode = function(textToBeDecoded){
  return textToBeDecoded;
};
 
 
/**
 * Create a new TextBase64QueueMessageEncoder object
 * @class
 * 
 * Encode from utf-8 string to base64 string
 * Decode from base64 string to utf-8 string.
 * 
 * @constructor
 * @extends {QueueMessageEncoder}
 */
function TextBase64QueueMessageEncoder(){
}
util.inherits(TextBase64QueueMessageEncoder, QueueMessageEncoder);
 
/**
 * Encode from utf-8 string to base64 string
 * @this TextBase64QueueMessageEncoder
 * 
 * @param   {string}    [input]               The target to be encoded.
 * 
 * @return {string}
 */
TextBase64QueueMessageEncoder.prototype.encode = function(input){
  return new Buffer(input, 'utf8').toString('base64');
};
 
/**
 * Decode from base64 string to utf-8 string.
 * @this TextBase64QueueMessageEncoder
 * 
 * @param   {string}    [textToBeDecoded]     The base64 string to be decoded.
 * 
 * @return {string}
 */
TextBase64QueueMessageEncoder.prototype.decode = function(textToDecode){
  return new Buffer(textToDecode, 'base64').toString('utf8');
};
 
 
/**
 * Create a new BinaryBase64QueueMessageEncoder object
 * @class
 * 
 * Encode from binary buffer to base64 string
 * Decode from base64 string to binary buffer.
 * 
 * @constructor
 * @extends {QueueMessageEncoder}
 */
function BinaryBase64QueueMessageEncoder(){
}
util.inherits(BinaryBase64QueueMessageEncoder, QueueMessageEncoder);
 
/**
 * Encode from binary buffer string to base64 string
 * @this BinaryBase64QueueMessageEncoder
 * 
 * @param   {Buffer}    [input]               The target to be encoded.
 * 
 * @return {string}
 */
BinaryBase64QueueMessageEncoder.prototype.encode = function(input){
  return input.toString('base64');
};
 
 
/**
 * Decode from base64 string to binary buffer.
 * @this BinaryBase64QueueMessageEncoder
 * 
 * @param   {string}    [textToBeDecoded]     The base64 string to be decoded.
 * 
 * @return {Buffer}
 */
BinaryBase64QueueMessageEncoder.prototype.decode = function(textToDecode){
  return new Buffer(textToDecode, 'base64');
};
 
 
/**
 * Create a new TextXmlQueueMessageEncoder object
 * @class
 * 
 * Encode utf-8 string by escaping the xml markup characters.
 * Decode from utf-8 string by unescaping the xml markup characters.
 * 
 * @constructor
 * @extends {QueueMessageEncoder}
 */
function TextXmlQueueMessageEncoder(){
}
util.inherits(TextXmlQueueMessageEncoder, QueueMessageEncoder);
 
/**
 * Encode utf-8 string by escaping the xml markup characters.
 * @this TextXmlQueueMessageEncoder
 * 
 * @param   {string}    [input]               The target to be encoded.
 * 
 * @return {string}
 */
TextXmlQueueMessageEncoder.prototype.encode = function(input){
  return input.replace(/&/gm, '&amp;')
    .replace(/</gm, '&lt;')
    .replace(/>/gm, '&gt;')
    .replace(/"/gm, '&quot;')
    .replace(/'/gm, '&apos;');
};
 
/**
 * Decode from utf-8 string by unescaping the xml markup characters.
 * @this TextXmlQueueMessageEncoder
 * 
 * @param   {string}    [textToBeDecoded]     The base64 string to be decoded.
 * 
 * @return {string}
 */
TextXmlQueueMessageEncoder.prototype.decode = function(textToDecode){
  return textToDecode.replace(/&amp;/gm, '&')
    .replace(/&lt;/gm, '<')
    .replace(/&gt;/gm, '>')
    .replace(/&quot;/gm, '"')
    .replace(/&apos;/gm, '\'');
};
 
module.exports = QueueMessageEncoder;
module.exports.TextBase64QueueMessageEncoder = TextBase64QueueMessageEncoder;
module.exports.BinaryBase64QueueMessageEncoder = BinaryBase64QueueMessageEncoder;
module.exports.TextXmlQueueMessageEncoder = TextXmlQueueMessageEncoder;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/queue/queueservice.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/queue/queueservice.js

Statements: 9.59% (47 / 490)      Branches: 0% (0 / 116)      Functions: 0% (0 / 106)      Lines: 10.44% (47 / 450)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468                                  1 1 1   1 1 1 1   1 1 1 1 1 1     1 1 1 1 1                                                         1                                           1                                           1                                                                                                         1                                                 1                                                       1                                                           1                                                                                                                                                                             1                                                   1                                                                                                                                   1                                                                                                                   1                                                                                       1                                                                                                                 1                                                                                                                 1                                                                                                                                       1                                                                                                                                                                         1                                                                                                           1                                                                                             1                                                                           1                                                                                           1                                                                                                         1                                                                                                   1                                                                                                                                             1                                                                                                                                                             1                                                                                                                       1                                                                             1                                                                                         1                                                                                                                                                             1                 1    
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var util = require('util');
var _ = require('underscore');
var extend = require('extend');
 
var azureCommon = require('./../../common/common');
var azureutil = azureCommon.util;
var SR = azureCommon.SR;
var validate = azureCommon.validate;
 
var StorageServiceClient = azureCommon.StorageServiceClient;
var WebResource = azureCommon.WebResource;
var Constants = azureCommon.Constants;
var QueryStringConstants = Constants.QueryStringConstants;
var HeaderConstants = Constants.HeaderConstants;
var RequestLocationMode = Constants.RequestLocationMode;
 
// Models requires
var QueueResult = require('./models/queueresult');
var AclResult = azureCommon.AclResult;
var QueueMessageResult = require('./models/queuemessageresult');
var QueueMessageEncoder = require('./queuemessageencoder');
var ServiceStatsParser = azureCommon.ServiceStatsParser;
 
/**
* Creates a new QueueService object.
* If no connection string or storageaccount and storageaccesskey are provided,
* the AZURE_STORAGE_CONNECTION_STRING or AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables will be used.
* @class
* The QueueService class is used to perform operations on the Microsoft Azure Queue Service.
* 
* For more information on using the Queue Service, as well as task focused information on using it from a Node.js application, see
* [How to Use the Queue Service from Node.js](http://azure.microsoft.com/en-us/documentation/articles/storage-nodejs-how-to-use-queues/).
* The following defaults can be set on the Queue service.
* messageEncoder                                      The message encoder to specify how QueueService encodes and decodes the queue message. Default is `[TextXmlQueueMessageEncoder]{@link TextXmlQueueMessageEncoder}`.
* defaultTimeoutIntervalInMs                          The default timeout interval, in milliseconds, to use for request made via the Queue service.
* defaultClientRequestTimeoutInMs                     The default timeout of client requests, in milliseconds, to use for the request made via the Queue service.
* defaultMaximumExecutionTimeInMs                     The default maximum execution time across all potential retries, for requests made via the Queue service.
* defaultLocationMode                                 The default location mode for requests made via the Queue service.
* useNagleAlgorithm                                   Determines whether the Nagle algorithm is used for requests made via the Queue service; true to use the  
*                                                     Nagle algorithm; otherwise, false. The default value is false.
* @constructor
* @augments {StorageServiceClient}
*
* @param {string} [storageAccountOrConnectionString]  The storage account or the connection string.
* @param {string} [storageAccessKey]                  The storage access key.
* @param {string|object} [host]                       The host address. To define primary only, pass a string. 
*                                                     Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host.
* @param {string} [sasToken]                          The Shared Access Signature token.
* @param {string} [endpointSuffix]                    The endpoint suffix.
*/
function QueueService(storageAccountOrConnectionString, storageAccessKey, host, sasToken, endpointSuffix) {
  var storageServiceSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey, host, sasToken, endpointSuffix);
 
  QueueService['super_'].call(this,
    storageServiceSettings._name,
    storageServiceSettings._key,
    storageServiceSettings._queueEndpoint,
    storageServiceSettings._usePathStyleUri,
    storageServiceSettings._sasToken);
 
  if (this.anonymous) {
    throw new Error(SR.ANONYMOUS_ACCESS_BLOBSERVICE_ONLY);
  }
  
  /**
   * @property {boolean} QueueService#messageEncoder
   * @defaultvalue      {QueueMessageEncoder}     `[TextXmlQueueMessageEncoder]{@link TextXmlQueueMessageEncoder}`.
   * The message encoder to specify how QueueService encodes and decodes the queue message. Default is `[TextXmlQueueMessageEncoder]{@link TextXmlQueueMessageEncoder}`.
   */
  this.messageEncoder = new QueueMessageEncoder.TextXmlQueueMessageEncoder();
}
 
util.inherits(QueueService, StorageServiceClient);
 
/**
* Gets the service stats for a storage account’s Queue service.
*
* @this {QueueService}
* @param {object}       [options]                                         The request options.
* @param {LocationMode} [options.locationMode]                            Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}          [options.timeoutIntervalInMs]                     The server timeout interval, in milliseconds, to use for the request.
* @param {int}          [options.clientRequestTimeoutInMs]                The timeout of client requests, in milliseconds, to use for the request.
* @param {int}          [options.maximumExecutionTimeInMs]                The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}       [options.clientRequestId]                         A string that represents the client request ID with a 1KB character limit.
* @param {bool}         [options.useNagleAlgorithm]                       Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}  callback                                        `error` will contain information
*                                                                         if an error occurs; otherwise, `[result]{@link ServiceStats}`
*                                                                         will contain the stats and `response`
*                                                                         will contain information related to this operation.
*/
QueueService.prototype.getServiceStats = function (optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('getServiceStats', function (v) {
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.get()
    .withQueryOption(QueryStringConstants.COMP, 'stats')
    .withQueryOption(QueryStringConstants.RESTYPE, 'service');
 
  options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY;
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.serviceStatsResult = null;
    if (!responseObject.error) {
      responseObject.serviceStatsResult = ServiceStatsParser.parse(responseObject.response.body.StorageServiceStats);
    }
 
    // function to be called after all filters
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.serviceStatsResult, returnObject.response);
    };
 
    // call the first filter
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Gets the properties of a storage account’s Queue service, including Microsoft Azure Storage Analytics.
*
* @this {QueueService}
* @param {object}             [options]                                 The request options.
* @param {LocationMode}       [options.locationMode]                    Specifies the location mode used to decide which location the request should be sent to. 
*                                                                       Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]             The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]        The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]        The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                       The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                       execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                 A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]               Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                       The default value is false.
* @param {errorOrResult}  callback                                      `error` will contain information
*                                                                       if an error occurs; otherwise, `[result]{@link ServiceProperties}`
*                                                                       will contain the properties and `response`
*                                                                       will contain information related to this operation.
*/
QueueService.prototype.getServiceProperties = function (optionsOrCallback, callback) {
  return this.getAccountServiceProperties(optionsOrCallback, callback);
};
 
/**
* Sets the properties of a storage account’s Queue service, including Microsoft Azure Storage Analytics.
* You can also use this operation to set the default request version for all incoming requests that do not have a version specified.
*
* @this {QueueService}
* @param {object}             serviceProperties                        The service properties.
* @param {object}             [options]                                The request options.
* @param {LocationMode}       [options.locationMode]                   Specifies the location mode used to decide which location the request should be sent to. 
*                                                                      Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]            The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]       The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]       The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                      The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                      execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]              Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                      The default value is false.
* @param {errorOrResponse}  callback                                   `error` will contain information
*                                                                      if an error occurs; otherwise, `response`
*                                                                      will contain information related to this operation.
*/
QueueService.prototype.setServiceProperties = function (serviceProperties, optionsOrCallback, callback) {
  return this.setAccountServiceProperties(serviceProperties, optionsOrCallback, callback);
};
 
/**
* Lists a segment containing a collection of queue items whose names begin with the specified prefix under the given account.
*
* @this {QueueService}
* @param {object}             currentToken                                A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {object}             [options]                                   The request options.
* @param {int}                [options.maxResults]                        Specifies the maximum number of queues to return per call to Azure storage. This does NOT affect list size returned by this function. (maximum: 5000)
* @param {string}             [options.include]                           Include this parameter to specify that the queue's metadata be returned as part of the response body. (allowed values: '', 'metadata')
*                                                                         **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}  callback                                        `error` will contain information
*                                                                         if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. 
*                                                                         `entries`  gives a list of `[queues]{@link QueueResult}` and the `continuationToken` is used for the next listing operation.
*                                                                         `response` will contain information related to this operation.
*/
QueueService.prototype.listQueuesSegmented = function (currentToken, optionsOrCallback, callback) {
  this.listQueuesSegmentedWithPrefix(null /* prefix */, currentToken, optionsOrCallback, callback);
};
 
/**
* Lists a segment containing a collection of queue items  under the given account.
*
* @this {QueueService}
* @param {string}             prefix                                      The prefix of the queue name.
* @param {object}             currentToken                                A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.* @param {string}             [options.prefix]                  Filters the results to return only queues whose name begins with the specified prefix.
* @param {object}             [options]                                   The request options.
* @param {string}             [options.marker]                            String value that identifies the portion of the list to be returned with the next list operation.
* @param {int}                [options.maxResults]                        Specifies the maximum number of queues to return per call to Azure storage. This does NOT affect list size returned by this function. (maximum: 5000)
* @param {string}             [options.include]                           Include this parameter to specify that the queue's metadata be returned as part of the response body. (allowed values: '', 'metadata')
*                                                                         **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}  callback                                        `error` will contain information
*                                                                         if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. 
*                                                                         `entries`  gives a list of `[queues]{@link QueueResult}` and the `continuationToken` is used for the next listing operation.
*                                                                         `response` will contain information related to this operation.
*/
QueueService.prototype.listQueuesSegmentedWithPrefix = function (prefix, currentToken, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('listQueuesSegmentedWithPrefix', function (v) {
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.get();
  webResource.withQueryOption(QueryStringConstants.COMP, 'list')
    .withQueryOption(QueryStringConstants.MAX_RESULTS, options.maxResults)
    .withQueryOption(QueryStringConstants.INCLUDE, options.include)
    .withQueryOption(QueryStringConstants.PREFIX, prefix);
 
  if(!azureutil.objectIsNull(currentToken)) {
    webResource.withQueryOption(QueryStringConstants.MARKER, currentToken.nextMarker);
  }
 
  options.requestLocationMode = azureutil.getNextListingLocationMode(currentToken);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.listQueuesResult = null;
 
    if (!responseObject.error) {
      responseObject.listQueuesResult = {
        entries: null,
        continuationToken: null
      };
      responseObject.listQueuesResult.entries = [];
      var queues = [];
 
      if (responseObject.response.body.EnumerationResults.Queues && responseObject.response.body.EnumerationResults.Queues.Queue) {
        queues = responseObject.response.body.EnumerationResults.Queues.Queue;
 
        if (!_.isArray(queues)) {
          queues = [ queues ];
        }
 
        queues.forEach(function (currentQueue) {
          var queueResult = QueueResult.parse(currentQueue);
          responseObject.listQueuesResult.entries.push(queueResult);
        });
 
        if(responseObject.response.body.EnumerationResults.NextMarker) {
          responseObject.listQueuesResult.continuationToken = {
            nextMarker: null,
            targetLocation: null
          };
 
          responseObject.listQueuesResult.continuationToken.nextMarker = responseObject.response.body.EnumerationResults.NextMarker;
          responseObject.listQueuesResult.continuationToken.targetLocation = responseObject.targetLocation;
        }
      }
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.listQueuesResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Checks to see if a queue exists.
*
* @this {QueueService}
* @param {string}             queue                                       The queue name.
* @param {object}             [options]                                   The request options.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {Function(error, result, response)}  callback                    `error` will contain information
*                                                                         if an error occurs; otherwise, `[result]{@link QueueResult}` will contain
*                                                                         the queue information including `exists` boolean member.
*                                                                         `response` will contain information related to this operation.
*/
QueueService.prototype.doesQueueExist = function (queue, optionsOrCallback, callback) {
  this._doesQueueExist(queue, false, optionsOrCallback, callback);
};
 
/**
* Creates a new queue under the given account.
*
* @this {QueueService}
* @param {string}             queue                                       The queue name.
* @param {object}             [options]                                   The request options.
* @param {object}             [options.metadata]                          The metadata key/value pairs.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}  callback                                        `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link QueueResult}` will contain
*                                                                         the queue information.
*                                                                         `response` will contain information related to this operation.
*/
QueueService.prototype.createQueue = function (queue, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('createQueue', function (v) {
    v.string(queue, 'queue');
    v.queueNameIsValid(queue);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.put(queue);
  if (options) {
    webResource.addOptionalMetadataHeaders(options.metadata);
  }
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.queueResult = null;
    if (!responseObject.error) {
      responseObject.queueResult = new QueueResult(queue);
      if (options && options.metadata) {
        responseObject.queueResult.metadata = options.metadata;
      }
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.queueResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Creates a new queue under the given account if it doesn't exist.
*
* @this {QueueService}
* @param {string}             queue                                       The queue name.
* @param {object}             [options]                                   The request options.
* @param {object}             [options.metadata]                          The metadata key/value pairs.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}  callback                                       `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link QueueResult}` will contain 
*                                                                         the queue information including `created` boolean member and 
*                                                                         `response` will contain information related to this operation.
*
* @example
* var azure = require('azure-storage');
* var queueService = azure.createQueueService();
* queueService.createQueueIfNotExists('taskqueue', function(error) {
*   if(!error) {
*     // Queue created or exists
*   }
* }); 
*/
QueueService.prototype.createQueueIfNotExists = function (queue, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('createQueueIfNotExists', function (v) {
    v.string(queue, 'queue');
    v.queueNameIsValid(queue);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var self = this;
  self._doesQueueExist(queue, true, options, function(error, result, response) {
    var exists = result.exists;
    result.created = false;
    delete result.exists;
    
    if (error) {
      callback(error, result, response);
    } else if (exists) {
      response.isSuccessful = true;
      callback(error, result, response);
    } else {
      self.createQueue(queue, options, function(createError, responseQueue, createResponse) {
        if (!createError) {
          responseQueue.created = true;
        }
        else if (createError && createError.statusCode === Constants.HttpConstants.HttpResponseCodes.Conflict && createError.code === Constants.QueueErrorCodeStrings.QUEUE_ALREADY_EXISTS) {
          createError = null;
          responseQueue.created = false;
          createResponse.isSuccessful = true;
        }
 
        callback(createError, responseQueue, createResponse);
      });
    }
  });
};
 
/**
* Permanently deletes the specified queue.
*
* @this {QueueService}
* @param {string}             queue                                       The queue name.
* @param {object}             [options]                                   The request options.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResponse}  callback                                      `error` will contain information if an error occurs; 
*                                                                         `response` will contain information related to this operation.
*/
QueueService.prototype.deleteQueue = function (queue, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('deleteQueue', function (v) {
    v.string(queue, 'queue');
    v.queueNameIsValid(queue);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.del(queue);
  var processResponseCallback = function (responseObject, next) {
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Permanently deletes the specified queue if it exists.
*
* @this {QueueService}
* @param {string}             queue                                       The queue name.
* @param {object}             [options]                                   The request options.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}  callback                                        `error` will contain information
*                                                                         if an error occurs; otherwise `result` will contain
*                                                                         'true' if the queue was deleted and 'false' if the queue did not exist.
*                                                                         `response` will contain information related to this operation.
*/
QueueService.prototype.deleteQueueIfExists = function (queue, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('deleteQueueIfExists', function (v) {
    v.string(queue, 'queue');
    v.queueNameIsValid(queue);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var self = this;
  self._doesQueueExist(queue, true, options, function existsCallback(error, existsResult, response) {
    if (error) {
      callback(error, existsResult.exists, response);
    } else if (!existsResult.exists) {
      response.isSuccessful = true;
      callback(error, false, response);
    } else {
      self.deleteQueue(queue, options, function(deleteError, deleteResponse) {
        var deleted;
        if (!deleteError) {
          deleted = true;
        } else if (deleteError && deleteError.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound && deleteError.code === Constants.QueueErrorCodeStrings.QUEUE_NOT_FOUND) {
          deleted = false;
          deleteError = null;
          deleteResponse.isSuccessful = true;
        }
 
        callback(deleteError, deleted, deleteResponse);
      });
    }
  });
};
 
/**
* Returns queue properties, including user-defined metadata.
* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive.
*
* @this {QueueService}
* @param {string}             queue                                       The queue name.
* @param {object}             [options]                                   The request options.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}  callback                                        `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link QueueResult}` will contain
*                                                                         the queue information.
*                                                                         `response` will contain information related to this operation.
*/
QueueService.prototype.getQueueMetadata = function (queue, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('getQueueMetadata', function (v) {
    v.string(queue, 'queue');
    v.queueNameIsValid(queue);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.get(queue)
    .withQueryOption(QueryStringConstants.COMP, 'metadata');
 
  options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
 
  var self = this;
  var processResponseCallback = function (responseObject, next) {
    responseObject.queueResult = null;
    if (!responseObject.error) {
      responseObject.queueResult = new QueueResult(queue);
      responseObject.queueResult.metadata = self.parseMetadataHeaders(responseObject.response.headers);
      responseObject.queueResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.queueResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Sets user-defined metadata on the specified queue. Metadata is associated with the queue as name-value pairs.
*
* @this {QueueService}
* @param {string}             queue                                       The queue name.
* @param {object}             metadata                                    The metadata key/value pairs.
* @param {object}             [options]                                   The request options.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}  callback                                        `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link QueueResult}` will contain
*                                                                         the queue information.
*                                                                         `response` will contain information related to this operation.
*/
QueueService.prototype.setQueueMetadata = function (queue, metadata, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('setQueueMetadata', function (v) {
    v.string(queue, 'queue');
    v.queueNameIsValid(queue);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.put(queue)
    .withQueryOption(QueryStringConstants.COMP, 'metadata')
    .addOptionalMetadataHeaders(metadata);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.queueResult = null;
    if (!responseObject.error) {
      responseObject.queueResult = new QueueResult(queue, metadata);
      responseObject.queueResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.queueResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Adds a new message to the back of the message queue. 
* The encoded message can be up to 64KB in size for versions 2011-08-18 and newer, or 8KB in size for previous versions. 
* Unencoded messages must be in a format that can be included in an XML request with UTF-8 encoding. 
* Queue messages are encoded using the `[TextXmlQueueMessageEncoder]{@link TextXmlQueueMessageEncoder}`. See queueService.messageEncoder to set encoder defaults. 
* 
* @this {QueueService}
* @param {string}             queue                                       The queue name.
* @param {string|Buffer}      messageText                                 The message text.
* @param {object}             [options]                                   The request options.
* @param {int}                [options.messageTimeToLive]                 The time-to-live interval for the message, in seconds. The maximum time-to-live allowed is 7 days. If this parameter is omitted, the default time-to-live is 7 days
* @param {int}                [options.visibilityTimeout]                 Specifies the new visibility timeout value, in seconds, relative to server time. The new value must be larger than or equal to 0, and cannot be larger than 7 days. The visibility timeout of a message cannot be set to a value later than the expiry time. visibilitytimeout should be set to a value smaller than the time-to-live value.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}      callback                                    `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link QueueMessageResult}` will contain
*                                                                         the message.
*                                                                         `response` will contain information related to this operation.
*
* @example
* var azure = require('azure-storage');
* var queueService = azure.createQueueService();
* queueService.createMessage('taskqueue', 'Hello world!', function(error) {
*   if(!error) {
*     // Message inserted
*   }
* });
*/
QueueService.prototype.createMessage = function (queue, messageText, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('createMessage', function (v) {
    v.string(queue, 'queue');
    v.queueNameIsValid(queue);
    v.callback(callback);
  });
 
  var xmlMessageDescriptor = QueueMessageResult.serialize(messageText, this.messageEncoder);
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.post(queue + '/messages')
    .withHeader(HeaderConstants.CONTENT_TYPE, 'application/atom+xml;charset="utf-8"')
    .withHeader(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(xmlMessageDescriptor, 'utf8'))
    .withQueryOption(QueryStringConstants.MESSAGE_TTL, options.messageTimeToLive)
    .withQueryOption(QueryStringConstants.VISIBILITY_TIMEOUT, options.visibilityTimeout)
    .withBody(xmlMessageDescriptor);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.queueMessageResults = [];
 
    if (responseObject.response && responseObject.response.body && responseObject.response.body.QueueMessagesList && responseObject.response.body.QueueMessagesList.QueueMessage) {
      var messages = responseObject.response.body.QueueMessagesList.QueueMessage;
 
      if (!_.isArray(messages)) {
        messages = [ messages ];
      }
 
      messages.forEach(function (message) {
        var queueMessageResult = QueueMessageResult.parse(message, this.messageEncoder);
        responseObject.queueMessageResults.push(queueMessageResult);
      });
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, responseObject.queueMessageResults[0], returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, webResource.body, options, processResponseCallback);
};
 
/**
* Retrieve messages from the queue and makes them invisible to other consumers.
*
* @this {QueueService}
* @param {string}             queue                                       The queue name.
* @param {object}             [options]                                   The request options.
* @param {int}                [options.numOfMessages]                     A nonzero integer value that specifies the number of messages to retrieve from the queue, up to a maximum of 32. By default, a single message is retrieved from the queue with this operation.
* @param {int}                [options.visibilityTimeout]                 Required if not peek only. Specifies the new visibility timeout value, in seconds, relative to server time. The new value must be larger than or equal to 0, and cannot be larger than 7 days. The visibility timeout of a message can be set to a value later than the expiry time.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}  callback                                        `error` will contain information
*                                                                         if an error occurs; otherwise `result` will contain
*                                                                         a list of `[messages]{@link QueueMessageResult}`.
*                                                                         `response` will contain information related to this operation.
*
* @example
* var azure = require('azure-storage');
* var queueService = azure.createQueueService();
* var queueName = 'taskqueue';
* queueService.getMessages(queueName, function(error, serverMessages) {
*   if(!error) {
*     // Process the message in less than 30 seconds, the message
*     // text is available in serverMessages[0].messagetext
*     queueService.deleteMessage(queueName, serverMessages[0].messageId, serverMessages[0].popReceipt, function(error) {
*       if(!error){
*           // Message deleted
*       }
*     });
*   }
* });
*/
QueueService.prototype.getMessages = function (queue, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('getMessages', function (v) {
    v.string(queue, 'queue');
    v.queueNameIsValid(queue);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  delete options.peekOnly;
  
  this._getOrPeekMessages(queue, options, callback);
};
 
/**
* Retrieves a message from the queue and makes it invisible to other consumers.
*
* @this {QueueService}
* @param {string}             queue                                       The queue name.
* @param {object}             [options]                                   The request options.
* @param {int}                [options.visibilityTimeout]                 Required if not peek only. Specifies the new visibility timeout value, in seconds, relative to server time. The new value must be larger than or equal to 0, and cannot be larger than 7 days. The visibility timeout of a message can be set to a value later than the expiry time.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}  callback                                        `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link QueueMessageResult}` will contain
*                                                                         the message.
*                                                                         `response` will contain information related to this operation.
*
* @example
* var azure = require('azure-storage');
* var queueService = azure.createQueueService();
* var queueName = 'taskqueue';
* queueService.getMessage(queueName, function(error, serverMessage) {
*   if(!error) {
*     // Process the message in less than 30 seconds, the message
*     // text is available in serverMessage.messagetext
*     queueService.deleteMessage(queueName, serverMessage.messageId, serverMessage.popReceipt, function(error) {
*       if(!error){
*           // Message deleted
*       }
*     });
*   }
* });
*/
QueueService.prototype.getMessage = function (queue, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('getMessage', function (v) {
    v.string(queue, 'queue');
    v.queueNameIsValid(queue);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  options.numOfMessages = 1;
  
  var finalCallback = function(error, messages, response){
    var message;
    if(messages && messages.length > 0){
      message = messages[0];
    }
    
    callback(error, message, response);
  };
  
  this.getMessages(queue, options, finalCallback);
};
 
/**
* Retrieves messages from the front of the queue, without changing the messages visibility.
*
* @this {QueueService}
* @param {string}             queue                                       The queue name.
* @param {object}             [options]                                   The request options.
* @param {int}                [options.numOfMessages]                     A nonzero integer value that specifies the number of messages to retrieve from the queue, up to a maximum of 32. By default, a single message is retrieved from the queue with this operation.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}  callback                                        `error` will contain information
*                                                                         if an error occurs; otherwise `result` will contain
*                                                                         `[messages]{@link QueueMessageResult}`.
*                                                                         `response` will contain information related to this operation.
*/
QueueService.prototype.peekMessages = function (queue, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('peekMessages', function (v) {
    v.string(queue, 'queue');
    v.queueNameIsValid(queue);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  options.peekOnly = true;
  delete options.visibilityTimeout;
  
  this._getOrPeekMessages(queue, options, callback);
};
 
/**
* Retrieves a message from the front of the queue, without changing the message visibility.
*
* @this {QueueService}
* @param {string}             queue                                       The queue name.
* @param {object}             [options]                                   The request options.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}  callback                                        `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link QueueMessageResult}` will contain
*                                                                         the message.
*                                                                         `response` will contain information related to this operation.
*/
QueueService.prototype.peekMessage = function (queue, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('peekMessage', function (v) {
    v.string(queue, 'queue');
    v.queueNameIsValid(queue);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  options.numOfMessages = 1;
  
  var finalCallback = function(error, messages, response){
    var message;
    if(messages && messages.length > 0){
      message = messages[0];
    }
    
    callback(error, message, response);
  };
  
  this.peekMessages(queue, options, finalCallback);
};
 
/**
* Deletes a specified message from the queue.
*
* @this {QueueService}
* @param {string}             queue                                       The queue name.
* @param {string}             messageId                                   The message identifier of the message to delete.
* @param {string}             popReceipt                                  A valid pop receipt value returned from an earlier call to the Get Messages or Update Message operation
* @param {object}             [options]                                   The request options.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResponse}  callback                                      `error` will contain information if an error occurs; 
*                                                                         `response` will contain information related to this operation.
*/
QueueService.prototype.deleteMessage = function (queue, messageId, popReceipt, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('deleteMessage', function (v) {
    v.string(queue, 'queue');
    v.queueNameIsValid(queue);
    v.callback(callback);
  });
 
  if (azureutil.objectIsNull(popReceipt)) {
    throw new Error(SR.INVALID_POP_RECEIPT);
  }
 
  if (azureutil.objectIsNull(messageId)) {
    throw new Error(SR.INVALID_MESSAGE_ID);
  }
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.del(queue + '/messages/' + messageId)
    .withQueryOption(QueryStringConstants.POP_RECEIPT, popReceipt, null, true);
 
  var processResponseCallback = function (responseObject, next) {
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Clears all messages from the queue.
*
* @this {QueueService}
* @param {string}             queue                                       The queue name.
* @param {object}             [options]                                   The request options.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResponse}  callback                                      `error` will contain information
*                                                                         if an error occurs; otherwise 
*                                                                         `response` will contain information related to this operation.
*/
QueueService.prototype.clearMessages = function (queue, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('clearMessages', function (v) {
    v.string(queue, 'queue');
    v.queueNameIsValid(queue);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.del(queue + '/messages');
 
  var processResponseCallback = function (responseObject, next) {
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Updates the visibility timeout of a message. You can also use this operation to update the contents of a message.
* A message must be in a format that can be included in an XML request with UTF-8 encoding, and the encoded message can be up to 64KB in size.
*
* @this {QueueService}
* @param {string}             queue                                       The queue name.
* @param {string}             messageId                                   The message identifier of the message to update.
* @param {string}             popReceipt                                  A valid pop receipt value returned from an earlier call to the Get Messages or Update Message operation
* @param {int}                visibilityTimeout                           Specifies the new visibility timeout value, in seconds, relative to server time. The new value must be larger than or equal to 0, and cannot be larger than 7 days. The visibility timeout of a message can be set to a value later than the expiry time.
* @param {object}             [options]                                   The request options.
* @param {object}             [options.messageText]                       The new message text.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}  callback                                        `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link QueueMessageResult}` will contain
*                                                                         the message result information.
*                                                                         `response` will contain information related to this operation.
*/
QueueService.prototype.updateMessage = function (queue, messageId, popReceipt, visibilityTimeout, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('updateMessage', function (v) {
    v.string(queue, 'queue');
    v.queueNameIsValid(queue);
    v.callback(callback);
  });
 
  if (azureutil.objectIsNull(popReceipt)) {
    throw new Error(SR.INVALID_POP_RECEIPT);
  }
 
  if (azureutil.objectIsNull(messageId)) {
    throw new Error(SR.INVALID_MESSAGE_ID);
  }
 
  var options = extend(true, {}, userOptions);
  var content = null;
  if (options.messageText) {
    content = QueueMessageResult.serialize(options.messageText, this.messageEncoder);
  }
 
  var contentLength = content ? Buffer.byteLength(content, 'utf8') : 0;
 
  var webResource = WebResource.put(queue + '/messages/' + messageId)
    .withHeader(HeaderConstants.CONTENT_TYPE, 'application/atom+xml;charset="utf-8"')
    .withHeader(HeaderConstants.CONTENT_LENGTH, contentLength)
    .withQueryOption(QueryStringConstants.POP_RECEIPT, popReceipt, null, true)
    .withQueryOption(QueryStringConstants.VISIBILITY_TIMEOUT, visibilityTimeout)
    .withBody(content);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.queueMessageResult = null;
    if (!responseObject.error) {
      responseObject.queueMessageResult = new QueueMessageResult(queue, messageId);
      responseObject.queueMessageResult.getPropertiesFromHeaders(responseObject.response.headers);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.queueMessageResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, webResource.body, options, processResponseCallback);
};
 
/**
* Gets the queue's ACL.
*
* @this {QueueService}
* @param {string}             queue                                       The queue name.
* @param {object}             [options]                                   The request options.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}  callback                                        `error` will contain information
*                                                                         if an error occurs; otherwise `[result]{@link QueueResult}` will contain
*                                                                         information for the queue.
*                                                                         `response` will contain information related to this operation.
*/
QueueService.prototype.getQueueAcl = function (queue, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('getQueueAcl', function (v) {
    v.string(queue, 'queue');
    v.queueNameIsValid(queue);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.get(queue)
    .withQueryOption(QueryStringConstants.COMP, 'acl');
 
  options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.queueResult = null;
    if (!responseObject.error) {
      responseObject.queueResult = new QueueResult(queue);
      responseObject.queueResult.getPropertiesFromHeaders(responseObject.response.headers);
      responseObject.queueResult.signedIdentifiers = AclResult.parse(responseObject.response.body);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.queueResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Updates the queue's ACL.
*
* @this {QueueService}
* @param {string}                             queue                                       The queue name.
* @property   {Object.<string, AccessPolicy>}    signedIdentifiers                           The container ACL settings. See `[AccessPolicy]{@link AccessPolicy}` for detailed information.
* @param {object}                             [options]                                   The request options.
* @param {LocationMode}                       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}                             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}                               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                                         The default value is false.
* @param {errorOrResult}  callback                                                        `error` will contain information
*                                                                                         if an error occurs; otherwise `[result]{@link QueueResult}` will contain
*                                                                                         information for the queue.
*                                                                                         `response` will contain information related to this operation.
* @example
* var azure = require('azure-storage');
* var SharedAccessPermissions = azure.QueueUtilities.SharedAccessPermissions;
* var queueService = azure.createQueueService();
* var sharedAccessPolicies = [
* {AccessPolicy: {
*     Permissions: PROCESS,
*     Start: startDate,
*     Expiry: expiryDate
*   },
*   Id: processOnly,
* },
* {AccessPolicy: {
*     Permissions: SharedAccessPermissions.PROCESS + SharedAccessPermissions.DELETE,
*     Start: startDate,
*     Expiry: expiryDate
*   },
*   Id: processAndDelete,
* }];
* 
* queueService.setQueueAcl(queueName, sharedAccessPolicies, function(error, queueResult, response) {
*     // do whatever
* });
*/
QueueService.prototype.setQueueAcl = function (queue, signedIdentifiers, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('setQueueAcl', function (v) {
    v.string(queue, 'queue');
    v.queueNameIsValid(queue);
    v.callback(callback);
  });
  
  var options = extend(true, {}, userOptions);
 
  var policies = null;
  if (signedIdentifiers) {
    if(_.isArray(signedIdentifiers)) {
      throw new TypeError(SR.INVALID_SIGNED_IDENTIFIERS);
    }
    policies = AclResult.serialize(signedIdentifiers);
  }
 
  var webResource = WebResource.put(queue)
    .withQueryOption(QueryStringConstants.COMP, 'acl')
    .withHeader(HeaderConstants.CONTENT_LENGTH, !azureutil.objectIsNull(policies) ? Buffer.byteLength(policies) : 0)
    .withBody(policies);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.containerResult = null;
    if (!responseObject.error) {
      responseObject.queueResult = new QueueResult(queue);
      responseObject.queueResult.getPropertiesFromHeaders(responseObject.response.headers);
      if (signedIdentifiers) {
        responseObject.queueResult.signedIdentifiers = signedIdentifiers;
      }
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.queueResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, webResource.body, options, processResponseCallback);
};
 
/**
* Retrieves a shared access signature token.
*
* @this {QueueService}
* @param {string}                   queue                                               The queue name.
* @param {object}                   sharedAccessPolicy                                  The shared access policy.
* @param {string}                   [sharedAccessPolicy.Id]                             The signed identifier.
* @param {object}                   [sharedAccessPolicy.AccessPolicy.Permissions]       The permission type.
* @param {date|string}              [sharedAccessPolicy.AccessPolicy.Start]             The time at which the Shared Access Signature becomes valid (The UTC value will be used).
* @param {date|string}              [sharedAccessPolicy.AccessPolicy.Expiry]            The time at which the Shared Access Signature becomes expired (The UTC value will be used).
* @param {string}                   [sharedAccessPolicy.AccessPolicy.IPAddressOrRange]  An IP address or a range of IP addresses from which to accept requests. When specifying a range, note that the range is inclusive.
* @param {string}                   sharedAccessPolicy.AccessPolicy.Protocols           The protocols permitted for a request made with the account SAS. 
*                                                                                       Possible values are both HTTPS and HTTP (https,http) or HTTPS only (https). The default value is https,http.
* @return {string}                                                                      The shared access signature query string. Note this string does not contain the leading "?".
*/
QueueService.prototype.generateSharedAccessSignature = function (queue, sharedAccessPolicy) {
  // check if the QueueService is able to generate a shared access signature
  if (!this.storageCredentials || !this.storageCredentials.generateSignedQueryString) {
    throw new Error(SR.CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY);
  }
 
  validate.validateArgs('generateSharedAccessSignature', function (v) {
    v.string(queue, 'queue');
    v.queueNameIsValid(queue);
    v.object(sharedAccessPolicy, 'sharedAccessPolicy');
  });
 
  return this.storageCredentials.generateSignedQueryString(Constants.ServiceType.Queue, queue, sharedAccessPolicy, null);
};
 
/**
* Checks to see if a queue exists.
* @ignore
*
* @this {QueueService}
* @param {string}             queue                                       The queue name.
* @param {string}             primaryOnly                                 If true, the request will be executed against the primary storage location.
* @param {object}             [options]                                   The request options.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]          The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {Function(error, result, response)}         callback             `error` will contain information
*                                                                         if an error occurs; otherwise, `result` will contain
*                                                                         the queue information including `exists` boolean member
*                                                                         and `response` will contain information related to this operation.
*
*/
QueueService.prototype._doesQueueExist = function (queue, primaryOnly, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('doesQueueExist', function(v) {
    v.string(queue, 'queue');
    v.queueNameIsValid(queue);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  var webResource = WebResource.head(queue)
    .withQueryOption(QueryStringConstants.COMP, 'metadata');
 
  if(primaryOnly === false) {
    options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY;
  }
 
  var processResponseCallback = function(responseObject, next) {
    responseObject.queueResult = new QueueResult(queue);
    responseObject.queueResult.exists = false;
    
    if (!responseObject.error) {
      responseObject.queueResult.exists = true;
      responseObject.queueResult.getPropertiesFromHeaders(responseObject.response.headers);
      
    } else if (responseObject.error && responseObject.error.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound) {
      responseObject.error = null;
      responseObject.queueResult.exists = false;
      responseObject.response.isSuccessful = true;
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.queueResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
 * @ignore
 */
QueueService.prototype._getOrPeekMessages = function (queue, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('_getOrPeekMessages', function (v) {
    v.string(queue, 'queue');
    v.queueNameIsValid(queue);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
 
  if (!options.numOfMessages) {
    options.numOfMessages = 1;
  }
 
  var webResource = WebResource.get(queue + '/messages')
    .withQueryOption(QueryStringConstants.NUM_OF_MESSAGES, options.numOfMessages)
    .withQueryOption(QueryStringConstants.VISIBILITY_TIMEOUT, options.visibilityTimeout)
    .withQueryOption(QueryStringConstants.PEEK_ONLY, options.peekOnly);
 
  if (options.peekOnly) {
    // For peek message, it's a read-only action and can be performed against secondary endpoint.
    options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY;
  }
 
 
  var messageEncoder = this.messageEncoder;
  var processResponseCallback = function (responseObject, next) {
    responseObject.queueMessageResults = null;
 
    if (!responseObject.error) {
      responseObject.queueMessageResults = [];
 
      if (responseObject.response.body.QueueMessagesList && responseObject.response.body.QueueMessagesList.QueueMessage) {
        var messages = responseObject.response.body.QueueMessagesList.QueueMessage;
 
        if (!_.isArray(messages)) {
          messages = [ messages ];
        }
 
        messages.forEach(function (message) {
          var queueMessageResult = QueueMessageResult.parse(message, messageEncoder);
          responseObject.queueMessageResults.push(queueMessageResult);
        });
      }
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.queueMessageResults, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Retrieves a queue URL.
*
* @param {string}                   queue                    The queue name.
* @param {string}                   [sasToken]               The Shared Access Signature token.
* @param {boolean}                  [primary]                A boolean representing whether to use the primary or the secondary endpoint.
* @return {string}                                           The formatted URL string.
* @example
* var azure = require('azure-storage');
* var queueService = azure.createQueueService();
* var sharedAccessPolicy = {
*   AccessPolicy: {
*     Permissions: azure.QueueUtilities.SharedAccessPermissions.READ,
*     Start: startDate,
*     Expiry: expiryDate
*   },
* };
* 
* var sasToken = queueService.generateSharedAccessSignature(queue, sharedAccessPolicy);
* var sasUrl = queueService.getUrl(queue, sasToken);
*/
QueueService.prototype.getUrl = function (queue, sasToken, primary) {
  validate.validateArgs('getUrl', function (v) {
    v.string(queue, 'queue');
    v.queueNameIsValid(queue);
  });
 
  return this._getUrl(queue, sasToken, primary);
};
 
module.exports = QueueService;
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/queue/queueutilities.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/queue/queueutilities.js

Statements: 100% (3 / 3)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (3 / 3)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40                                  1           1                             1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Expose 'QueueUtilities'.
exports = module.exports;
 
/**
* Defines enums for use with the Queue service.
* @namespace QueueUtilities
*/
var QueueUtilities = {
	/**
  * Permission types.
  *
  * @const
  * @enum {string}
  */
  SharedAccessPermissions: {
    READ: 'r',
    ADD: 'a',
    UPDATE: 'u',
    PROCESS: 'p'
  }
};
 
module.exports = QueueUtilities;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/queue/models/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/queue/models/

Statements: 24.62% (16 / 65)      Branches: 0% (0 / 36)      Functions: 0% (0 / 9)      Lines: 24.62% (16 / 65)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/lib/services/queue/models/
File Statements Branches Functions Lines
queuemessageresult.js 23.26% (10 / 43) 0% (0 / 24) 0% (0 / 5) 23.26% (10 / 43)
queueresult.js 27.27% (6 / 22) 0% (0 / 12) 0% (0 / 4) 27.27% (6 / 22)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/queue/models/queuemessageresult.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/queue/models/queuemessageresult.js

Statements: 23.26% (10 / 43)      Branches: 0% (0 / 24)      Functions: 0% (0 / 5)      Lines: 23.26% (10 / 43)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132                                  1 1 1 1   1                                         1                                         1                                                           1                                             1                         1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var azureCommon = require('./../../../common/common');
var azureutil = azureCommon.util;
var xmlbuilder = azureCommon.xmlbuilder;
var Constants = azureCommon.Constants;
 
var HeaderConstants = Constants.HeaderConstants;
 
/**
* Creates a new QueueMessageResult object.
* @class
* The QueueMessageResult class is used to store the queue message information.
* 
* @property   {string}                      queue                           The queue name.
* @property   {string}                      messageId                       The message id.
* @property   {string}                      popReceipt                      The pop receipt.
* @property   {string}                      messageText                     The message text.
* @property   {string}                      timeNextVisible                 The time next visible.
* @property   {string}                      insertionTime                   The insertion time.
* @property   {string}                      expirationTime                  The expiration time.
* @property   {number}                      dequeueCount                    The dequeue count.
 * 
* @constructor
* @param {string} [queue]                   The queue name.
* @param {string} [messageId]               The message id.
* @param {string} [popReceipt]              The pop receipt.
*/
function QueueMessageResult(queue, messageId, popReceipt) {
  if (queue) {
    this.queue = queue;
  }
 
  if (messageId) {
    this.messageId = messageId;
  }
 
  if (popReceipt) {
    this.popReceipt = popReceipt;
  }
}
 
/**
* Builds an XML representation for a queue message
*
* @param  {string}  messageJs    The queue message.
* @param  {QueueMessageEncoder}  The message encoder.
* @return {string} The XML queue message.
*/
QueueMessageResult.serialize = function (messageJs, encoder) {
  var doc = xmlbuilder.create();
  doc = doc.begin(Constants.QueueConstants.QUEUE_MESSAGE_ELEMENT, { version: '1.0', encoding: 'utf-8' });
 
  if (messageJs) {
    var message;
    if (encoder !== null && encoder !== undefined) {
      message = encoder.encode(messageJs);
    } else {
      message = messageJs;
    }
    
    doc.ele(Constants.QueueConstants.MESSAGE_TEXT_ELEMENT)
        .txt(message)
      .up();
  } else {
    doc.ele(Constants.QueueConstants.MESSAGE_TEXT_ELEMENT).up();
  }
 
  return doc.doc().toString();
};
 
 
/**
* Pase the XML representation of a queue message to a QueueMessageResult object.
*
* @param  {Object}  messageXml   The XML representation of the queue message.
* @param  {QueueMessageEncoder}  The message encoder.
* @return {QueueMessageResult}   The QueueMessageResult object.
*/
QueueMessageResult.parse = function (messageXml, encoder) {
  var queueMessageResult = new QueueMessageResult();
  for (var property in messageXml) {
    if (property === Constants.QueueConstants.MESSAGE_TEXT_ELEMENT) {
      if (encoder !== null && encoder !== undefined) {
        queueMessageResult.messageText = encoder.decode(messageXml[property]);
      } else {
        queueMessageResult.messageText = messageXml[property];
      }
    } else {
      var resultPropertyName = azureutil.normalizePropertyNameFromXML(property);
      queueMessageResult[resultPropertyName] = messageXml[property];
    }
  }
 
  // Convert dequeueCount to number
  if (queueMessageResult.dequeueCount) {
    queueMessageResult.dequeueCount = parseInt(queueMessageResult.dequeueCount);
  }
 
  return queueMessageResult;
};
 
QueueMessageResult.prototype.getPropertiesFromHeaders = function (headers) {
  var self = this;
 
  var setmessagePropertyFromHeaders = function (messageProperty, headerProperty) {
    if (!self[messageProperty] && headers[headerProperty.toLowerCase()]) {
      self[messageProperty] = headers[headerProperty.toLowerCase()];
    }
  };
 
  setmessagePropertyFromHeaders('popReceipt', HeaderConstants.POP_RECEIPT);
  setmessagePropertyFromHeaders('timeNextVisible', HeaderConstants.TIME_NEXT_VISIBLE);
};
 
module.exports = QueueMessageResult;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/queue/models/queueresult.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/queue/models/queueresult.js

Statements: 27.27% (6 / 22)      Branches: 0% (0 / 12)      Functions: 0% (0 / 4)      Lines: 27.27% (6 / 22)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73                                  1 1                               1                   1                     1                               1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var Constants = require('./../../../common/common').Constants;
var HeaderConstants = Constants.HeaderConstants;
 
/**
* Creates a new QueueResult object.
* @class
* The QueueResult class is used to store the queue information.
* 
* @property   {string}                      name                                  The queue name.
* @property   {object}                      metadata                              The metadata key/value pair.
* @property   {number}                      approximateMessageCount               The approximate number of messages in the queue. This number is not lower than the actual number of messages in the queue, but could be higher.
* @property   {Object.<string, AccessPolicy>}  signedIdentifiers                     The container ACL settings. See `[AccessPolicy]{@link AccessPolicy}` for detailed information.
 * 
* @constructor
* @param {string} [name]                    The queue name.
* @param {string} [metadata]                The metadata key/value pair.
*/
function QueueResult(name, metadata) {
  if (name) {
    this.name = name;
  }
 
  if (metadata) {
    this.metadata = metadata;
  }
}
 
QueueResult.parse = function (messageXml) {
  var queueResult = new QueueResult();
  for (var property in messageXml) {
    if (messageXml.hasOwnProperty(property)) {
      queueResult[property.toLowerCase()] = messageXml[property];
    }
  }
 
  return queueResult;
};
 
QueueResult.prototype.getPropertiesFromHeaders = function (headers) {
  var self = this;
 
  var setPropertyFromHeaders = function (queueProperty, headerProperty, typeConverterFunc) {
    if (!self[queueProperty] && headers[headerProperty.toLowerCase()]) {
      if(typeConverterFunc) {
        self[queueProperty] = typeConverterFunc(headers[headerProperty.toLowerCase()]);
      } else{
        self[queueProperty] = headers[headerProperty.toLowerCase()];
      }
    }
  };
 
  setPropertyFromHeaders('approximateMessageCount', HeaderConstants.APPROXIMATE_MESSAGES_COUNT, parseInt);
};
 
module.exports = QueueResult;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/

Statements: 18.96% (109 / 575)      Branches: 0% (0 / 159)      Functions: 0.79% (1 / 126)      Lines: 19.78% (109 / 551)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/
File Statements Branches Functions Lines
tablebatch.js 34.43% (21 / 61) 0% (0 / 14) 0% (0 / 15) 34.43% (21 / 61)
tablequery.js 29.63% (32 / 108) 0% (0 / 33) 0% (0 / 21) 29.63% (32 / 108)
tableservice.js 13.11% (51 / 389) 0% (0 / 110) 0% (0 / 80) 13.97% (51 / 365)
tableutilities.js 29.41% (5 / 17) 0% (0 / 2) 10% (1 / 10) 29.41% (5 / 17)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/tablebatch.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/tablebatch.js

Statements: 34.43% (21 / 61)      Branches: 0% (0 / 14)      Functions: 0% (0 / 15)      Lines: 34.43% (21 / 61)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211                                  1   1 1 1 1 1             1                 1                 1                 1                             1                                     1                 1                 1                 1                 1                 1                     1                                                                             1                   1                       1    
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var extend = require('extend');
 
var azureCommon = require('./../../common/common');
var SR = azureCommon.SR;
var validate = azureCommon.validate;
var Constants = azureCommon.Constants;
var TableConstants = Constants.TableConstants;
 
/**
* Creates a new TableBatch.
*
* @constructor
*/
function TableBatch() {
  this.operations = [];
  this.pk = null;
  this.retrieve = false;
}
 
/**
* Removes all of the operations from the batch.
*/
TableBatch.prototype.clear = function () {
  this.operations = [];
};
 
/**
* Returns a boolean value indicating weather there are operations in the batch.
*
* @return {Boolean} True if there are operations queued up; false otherwise.
*/
TableBatch.prototype.hasOperations = function () {
  return this.operations.length > 0;
};
 
/**
* Returns the number of operations in the batch.
*
* @return {number} The number of operations in the batch.
*/
TableBatch.prototype.size = function () {
  return this.operations.length;
};
 
/**
* Adds a retrieve operation to the batch. Note that this must be the only operation in the batch.
*
* @param {string}             partitionKey                                    The partition key.
* @param {string}             rowKey                                          The row key.
* @param {object}             [options]                                       The request options.
* @param {string}             [options.payloadFormat]                         The payload format to use for the request.
* @param {TableService~propertyResolver}  [options.propertyResolver]  The property resolver. Given the partition key, row key, property name, property value,
*                                                                             and the property Edm type if given by the service, returns the Edm type of the property.
* @param {Function(entity)} [options.entityResolver]                          The entity resolver. Given the single entity returned by the query, returns a modified object.
*/
TableBatch.prototype.retrieveEntity = function (partitionKey, rowKey, options) {
  var entity = { PartitionKey: {_: partitionKey, $: 'Edm.String'},
    RowKey: {_: rowKey, $: 'Edm.String'},
  };
  this.addOperation(TableConstants.Operations.RETRIEVE, entity, options);
};
 
/**
* Adds an insert operation to the batch.
*
* @param {object}             entity                                          The entity.
* @param {object}             [options]                                       The request options.
* @param {string}             [options.echoContent]                           Whether or not to return the entity upon a successful insert. Inserts only, default to false.
* @param {string}             [options.payloadFormat]                         The payload format to use for the request.
* @param {TableService~propertyResolver}  [options.propertyResolver]  The property resolver. Only applied if echoContent is true. Given the partition key, row key, property name, 
*                                                                             property value, and the property Edm type if given by the service, returns the Edm type of the property.
* @param {Function(entity)} [options.entityResolver]                          The entity resolver. Only applied if echoContent is true. Given the single entity returned by the insert, returns 
*                                                                             a modified object.
*/
TableBatch.prototype.insertEntity = function (entity, options) {
  this.addOperation(TableConstants.Operations.INSERT, entity, options);
};
 
/**
* Adds a delete operation to the batch.
*
* @param {object}             entity              The entity.
*/
TableBatch.prototype.deleteEntity = function (entity) {
  this.addOperation(TableConstants.Operations.DELETE, entity);
};
 
/**
* Adds a merge operation to the batch.
*
* @param {object}             entity              The entity.
*/
TableBatch.prototype.mergeEntity = function (entity) {
  this.addOperation(TableConstants.Operations.MERGE, entity);
};
 
/**
* Adds an replace operation to the batch.
*
* @param {object}             entity              The entity.
*/
TableBatch.prototype.replaceEntity = function (entity) {
  this.addOperation(TableConstants.Operations.REPLACE, entity);
};
 
/**
* Adds an insert or replace operation to the batch.
*
* @param {object}             entity              The entity.
*/
TableBatch.prototype.insertOrReplaceEntity = function (entity) {
  this.addOperation(TableConstants.Operations.INSERT_OR_REPLACE, entity);
};
 
/**
* Adds an insert or merge operation to the batch.
*
* @param {object}             entity              The entity.
*/
TableBatch.prototype.insertOrMergeEntity = function (entity) {
  this.addOperation(TableConstants.Operations.INSERT_OR_MERGE, entity);
};
 
/**
* Adds an operation to the batch after performing checks.
*
* @param {string}             operationType       The type of operation to perform. See Constants.TableConstants.Operations
* @param {object}             entity              The entity.
* @param {object}             [options]                                       The request options.
*/
TableBatch.prototype.addOperation = function (operationType, entity, options) {
  validate.validateArgs('addOperation', function (v) {
    v.object(entity, 'entity');
    v.object(entity.PartitionKey, 'entity.PartitionKey');
    v.object(entity.RowKey, 'entity.RowKey');
    v.stringAllowEmpty(entity.PartitionKey._, 'entity.PartitionKey._');
    v.stringAllowEmpty(entity.RowKey._, 'entity.RowKey._');
  });
 
  if(this.operations.length >= 100) {
    throw new Error(SR.BATCH_TOO_LARGE);
  }
 
  if (operationType === TableConstants.Operations.RETRIEVE) {
    if(this.hasOperations()) {
      throw new Error(SR.BATCH_ONE_RETRIEVE);
    } else {
      this.retrieve = true;
    }
  } else if (this.retrieve) {
    throw new Error(SR.BATCH_ONE_RETRIEVE);
  }
 
  if (!this.hasOperations()) {
    this.pk = entity.PartitionKey._;
  } else if (entity.PartitionKey._ !== this.pk) {
    throw new Error(SR.BATCH_ONE_PARTITION_KEY);
  }
 
  var copiedOptions = extend(true, {}, options);
  this.operations.push({type: operationType, entity: entity, options: copiedOptions});
};
 
/**
* Gets an operation from the batch. Returns null if the index does not exist.
*
* @param {number}             index           The index in the operations array at which to remove an element.
* @return {object}                            The removed operation.
*/
TableBatch.prototype.getOperation = function (index) {
  return this.operations[index];
};
 
/**
* Removes an operation from the batch. Returns null if the index does not exist.
*
* @param {number}             index           The index in the operations array at which to remove an element.
* @return {object}                            The removed operation.
*/
TableBatch.prototype.removeOperation = function (index) {
  var operation = this.operations.splice(index, 1)[0];
 
  // if the array is empty, unlock the partition key
  if (!this.hasOperations()) {
    this.pk = null;
    this.retrieve = false;
  }
 
  return operation;
};
 
module.exports = TableBatch;
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/tablequery.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/tablequery.js

Statements: 29.63% (32 / 108)      Branches: 0% (0 / 33)      Functions: 0% (0 / 21)      Lines: 29.63% (32 / 108)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420                                  1 1   1 1 1 1   1 1 1 1 1             1                           1                                                         1                                                         1                               1                             1                             1                             1                             1                             1                             1                             1                               1                             1                                       1                           1                                                           1                                                 1                                                 1                                                           1                           1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var _ = require('underscore');
var util = require('util');
 
var azureCommon = require('./../../common/common');
var azureutil = azureCommon.util;
var SR = azureCommon.SR;
var QueryStringConstants =  azureCommon.Constants.QueryStringConstants;
 
var edmHandler = require('./internal/edmhandler');
var TableUtilities = require('./tableutilities');
var QueryComparisons = TableUtilities.QueryComparisons;
var TableOperators = TableUtilities.TableOperators;
var EdmType = TableUtilities.EdmType;
 
/**
 * Creates a new TableQuery object.
 *
 * @constructor
 */
function TableQuery() {
  this._fields = [];
  this._where = [];
  this._top = null;
}
 
/**
* Specifies the select clause. If no arguments are given, all fields will be selected.
*
* @param {array} fields The fields to be selected.
* @return {TableQuery} A table query object with the select clause.
* @example
* var tableQuery = new TableQuery().select('field1', 'field2');
*/
TableQuery.prototype.select = function () {
  var self = this;
  if (arguments) {
    _.each(arguments, function (argument) {
      self._fields.push(argument);
    });
  }
 
  return this;
};
 
/**
 * Specifies the top clause.
 *
 * @param {int} top The number of items to fetch.
 * @return {TableQuery} A table query object with the top clause.
 * @example
 * var tableQuery = new TableQuery().top(10);
 *
 * // tasktable should already exist and have entities
 * tableService.queryEntities('tasktable', tableQuery, null \/*currentToken*\/, function(error, result) {
 *   if(!error) { 
 *     var entities = result.entities; // there will be 10 or less entities
 *     // do stuff with the returned entities if there are any
 *     // if result.continuationToken exists, to get the next 10 (or less) entities
 *     // call queryEntities as above, but with the returned token instead of null
 *   }
 * });
 */
TableQuery.prototype.top = function (top) {
  this._top = top;
  return this;
};
 
/**
 * Specifies the where clause.
 *
 * Valid type specifier strings include: ?string?, ?bool?, ?int32?, ?double?, ?date?, ?guid?, ?int64?, ?binary?
 * A type must be specified for guid, int64, and binaries or the filter produced will be incorrect.
 *
 * @param {string}       condition   The condition string.
 * @param {string|array} value       Value(s) to insert in question mark (?) parameters.
 * @return {TableQuery}  A table query object with the where clause.
 * @example
 * var tableQuery = new TableQuery().where(TableQuery.guidFilter('GuidField', QueryComparisons.EQUAL, guidVal));
 * OR
 * var tableQuery = new TableQuery().where('Name == ? or Name <= ?', name1, name2);
 * OR
 * var tableQuery = new TableQuery().where('Name == ?string? && Value == ?int64?, name1, int64Val);
 *
 * // tasktable should already exist and have entities
 * tableService.queryEntities('tasktable', tableQuery, null \/*currentToken*\/, function(error, result, response) {
 *   if(!error) { 
 *     var entities = result.entities;
 *     // do stuff with the returned entities if there are any
 *   }
 * });
 */
TableQuery.prototype.where = function (condition) {  
  this._where.push(TableQuery._encodeConditionString(condition, arguments));
  return this;
};
 
/**
 * Generates a property filter condition string for an 'int' value.
 *
 * @param {string}       propertyName   A string containing the name of the property to compare.
 * @param {string}       operation      A string containing the comparison operator to use. 
 *                                      See Constants.TableConstants.QueryComparisons for a list of allowed operations.
 * @param {string|int}   value          An 'int' containing the value to compare with the property.
 * @return {string} A string containing the formatted filter condition.
 * @example
 * var query = TableQuery.int32Filter('IntField', QueryComparisons.EQUAL, 5);
 */
TableQuery.int32Filter = function (propertyName, operation, value) {
  return TableQuery._concatFilterString(propertyName, operation, value, EdmType.INT32);
};
 
/**
 * Generates a property filter condition string for a 'int64' value.
 *
 * @param {string}       propertyName   A string containing the name of the property to compare.
 * @param {string}       operation      A string containing the comparison operator to use. 
 *                                      See Constants.TableConstants.QueryComparisons for a list of allowed operations.
 * @param {string|int64} value          An 'int64' containing the value to compare with the property.
 * @return {string} A string containing the formatted filter condition.
 * @example
 * var query = TableQuery.int64Filter('Int64Field', QueryComparisons.EQUAL, 123);
 */
TableQuery.int64Filter = function (propertyName, operation, value) {
  return TableQuery._concatFilterString(propertyName, operation, value, EdmType.INT64);
};
 
/**
 * Generates a property filter condition string for a 'double' value.
 *
 * @param {string}       propertyName   A string containing the name of the property to compare.
 * @param {string}       operation      A string containing the comparison operator to use. 
 *                                      See Constants.TableConstants.QueryComparisons for a list of allowed operations.
 * @param {string|double}value          A 'double' containing the value to compare with the property.
 * @return {string} A string containing the formatted filter condition.
 * @example
 * var query = TableQuery.doubleFilter('DoubleField', QueryComparisons.EQUAL, 123.45);
 */
TableQuery.doubleFilter = function (propertyName, operation, value) {
  return TableQuery._concatFilterString(propertyName, operation, value, EdmType.DOUBLE);
};
 
/**
 * Generates a property filter condition string for a 'boolean' value.
 *
 * @param {string}       propertyName   A string containing the name of the property to compare.
 * @param {string}       operation      A string containing the comparison operator to use. 
 *                                      See Constants.TableConstants.QueryComparisons for a list of allowed operations.
 * @param {string|boolean}       value          A 'boolean' containing the value to compare with the property.
 * @return {string} A string containing the formatted filter condition.
 * @example
 * var query = TableQuery.booleanFilter('BooleanField', QueryComparisons.EQUAL, false);
 */
TableQuery.booleanFilter = function (propertyName, operation, value) {
  return TableQuery._concatFilterString(propertyName, operation, value, EdmType.BOOLEAN);
};
 
/**
 * Generates a property filter condition string for a 'datetime' value.
 *
 * @param {string}       propertyName   A string containing the name of the property to compare.
 * @param {string}       operation      A string containing the comparison operator to use. 
 *                                      See Constants.TableConstants.QueryComparisons for a list of allowed operations.
 * @param {string|date}     value              A 'datetime' containing the value to compare with the property.
 * @return {string} A string containing the formatted filter condition.
 * @example
 * var query = TableQuery.dateFilter('DateTimeField', QueryComparisons.EQUAL, new Date(Date.UTC(2001, 1, 3, 4, 5, 6)));
 */
TableQuery.dateFilter = function (propertyName, operation, value) {
  return TableQuery._concatFilterString(propertyName, operation, value, EdmType.DATETIME);
};
 
/**
 * Generates a property filter condition string for a 'guid' value.
 *
 * @param {string}       propertyName   A string containing the name of the property to compare.
 * @param {string}       operation      A string containing the comparison operator to use. 
 *                                      See Constants.TableConstants.QueryComparisons for a list of allowed operations.
 * @param {string|guid}  value          A 'guid' containing the value to compare with the property.
 * @return {string} A string containing the formatted filter condition.
 * @example
 * var query = TableQuery.guidFilter('GuidField', QueryComparisons.EQUAL, guid.v1());
 */
TableQuery.guidFilter = function (propertyName, operation, value) {
  return TableQuery._concatFilterString(propertyName, operation, value, EdmType.GUID);
};
 
/**
 * Generates a property filter condition string for a 'binary' value.
 *
 * @param {string}       propertyName   A string containing the name of the property to compare.
 * @param {string}       operation      A string containing the comparison operator to use. 
 *                                      See Constants.TableConstants.QueryComparisons for a list of allowed operations.
 * @param {string|buffer}value          A 'buffer' containing the value to compare with the property.
 * @return {string} A string containing the formatted filter condition.
 * @example
 * var query = TableQuery.binaryFilter('BinaryField', QueryComparisons.EQUAL, new Buffer('hello'));
 */
TableQuery.binaryFilter = function (propertyName, operation, value) {
  return TableQuery._concatFilterString(propertyName, operation, value, EdmType.BINARY);
};
 
/**
 * Generates a property filter condition string.
 *
 * @param {string}       propertyName   A string containing the name of the property to compare.
 * @param {string}       operation      A string containing the comparison operator to use. 
 *                                      See Constants.TableConstants.QueryComparisons for a list of allowed operations.
 * @param {string}       value          A 'string' containing the value to compare with the property.
 * @return {string} A string containing the formatted filter condition.
 * @example
 * var query = TableQuery.stringFilter('StringField', QueryComparisons.EQUAL, 'name');
 */
TableQuery.stringFilter = function (propertyName, operation, value) {
  return TableQuery._concatFilterString(propertyName, operation, value, EdmType.STRING);
};
 
/**
 * Creates a filter condition using the specified logical operator on two filter conditions.
 *
 * @param {string}       filterA          A string containing the first formatted filter condition.
 * @param {string}       operatorString   A string containing the operator to use (AND, OR).
 * @param {string}       filterB          A string containing the second formatted filter condition.
 * @return {string} A string containing the combined filter expression.
 * @example
 * var filter1 = TableQuery.stringFilter('Name', QueryComparisons.EQUAL, 'Person');
 * var filter2 = TableQuery.booleanFilter('Visible', QueryComparisons.EQUAL, true);
 * var combinedFilter = TableQuery.combineFilters(filter1, TablUtilities.TableOperators.AND, filter2);
 */
TableQuery.combineFilters = function (filterA, operatorString, filterB) {
  return filterA + ' ' + operatorString + ' ' + filterB;
};
 
/**
 * Specifies an AND where condition.
 *
 * @param {string}       condition   The condition string.
 * @param {array}        arguments   Any number of arguments to be replaced in the condition by the question mark (?).
 * @return {TableQuery} A table query object with the and clause.
 * @example
 * var tableQuery = new TableQuery()
 *                      .where('Name == ? or Name <= ?', 'Person1', 'Person2');
 *                      .and('Age >= ?', 18);
 */
TableQuery.prototype.and = function (condition) {
  if (this._where.length === 0) {
    throw new Error(util.format(SR.QUERY_OPERATOR_REQUIRES_WHERE, 'AND'));
  }
 
  this._where.push(' and ' + TableQuery._encodeConditionString(condition, arguments));
  return this;
};
 
/**
 * Specifies an OR where condition.
 *
 * @param {string}       condition   The condition.
 * @param {array}        arguments   Any number of arguments to be replaced in the condition by the question mark (?).
 * @return {TableQuery} A table query object with the or clause.
 * @example
 * var tableQuery = new TableQuery()
 *                      .where('Name == ? or Name <= ?', 'Person1', 'Person2');
 *                      .or('Age >= ?', 18);
 */
TableQuery.prototype.or = function (condition) {
  if (this._where.length === 0) {
    throw new Error(util.format(SR.QUERY_OPERATOR_REQUIRES_WHERE, 'OR'));
  }
 
  this._where.push(' or ' + TableQuery._encodeConditionString(condition, arguments));
  return this;
};
 
/**
 * Returns the query string object for the query.
 *
 * @return {object} JSON object representing the query string arguments for the query.
 */
TableQuery.prototype.toQueryObject = function () {
  var query = {};
  if (this._fields.length > 0) {
    query[QueryStringConstants.SELECT] = this._fields.join(',');
  }
 
  if (this._where.length > 0) {
    query[QueryStringConstants.FILTER] = this._where.join('');
  }
 
  if (this._top) {
    query[QueryStringConstants.TOP] = this._top;
  }
 
  return query;
};
 
// Functions
 
/**
* Concat the filter string parameters.
*
* @param {string}       propertyName   A string containing the name of the property to compare.
* @param {string}       operation      A string containing the comparison operator to use. 
*                                      See Constants.TableConstants.QueryComparisons for a list of allowed operations.
* @param {object}       value          The value to compare with the property.
* @param {string}       type           A string EdmType of the property to compare.
* @return {string} A string containing the formatted filter condition.
* @ignore
*/
TableQuery._concatFilterString = function (propertyName, operation, value, type) {
  if (azureutil.objectIsNull(propertyName)) {
    throw new Error(util.format(SR.ARGUMENT_NULL_OR_UNDEFINED, 'propertyName'));
  }
 
  if (azureutil.objectIsNull(operation)) {
    throw new Error(util.format(SR.ARGUMENT_NULL_OR_UNDEFINED, 'operation'));
  }
 
  if (azureutil.objectIsNull(value)) {
    throw new Error(util.format(SR.ARGUMENT_NULL_OR_UNDEFINED, 'value'));
  }
 
  var serializedValue = edmHandler.serializeQueryValue(value, type);
  return propertyName + ' ' + operation + ' ' + serializedValue;
};
 
/**
 * Encodes a condition string.
 *
 * @param {string}       condition   The condition.
 * @param {array}        arguments   Any number of arguments to be replaced in the condition by the question mark (?).
 * @return {TableQuery} A table query object with the or clause
 * @ignore
 */
TableQuery._encodeConditionString = function (condition, args) {
  var encodedCondition = TableQuery._replaceOperators(condition);
  if (args.length > 1) {
    var sections = encodedCondition.split(/(\?string\?|\?int32\?|\?int64\?|\?bool\?|\?double\?|\?date\?|\?binary\?|\?guid\?|\?)/);
    var count = 1;
    for (var i = 0; i < sections.length && count < args.length; i++) {
      if (sections[i].indexOf('?') === 0) {
        var type = TableQuery._getEdmType(sections[i]);
        sections[i] = edmHandler.serializeQueryValue(args[count], type);
        count++;
      }
    }
    encodedCondition = sections.join('');
  }
 
  return encodedCondition;
};
 
/**
 * Converts the query string type to an Edm type.
 *
 * @param {string} type The type included in the query string.
 * @return {string} The EdmType.
 * @ignore
 */
TableQuery._getEdmType = function (type) {
  switch (type) {
    case '?binary?':
      return EdmType.BINARY;
    case '?int64?':
      return EdmType.INT64;
    case '?date?':
      return EdmType.DATETIME;
    case '?guid?':
      return EdmType.GUID;
    case '?int32?':
      return EdmType.INT32;
    case '?double?':
      return EdmType.DOUBLE;
    case '?bool?':
      return EdmType.BOOLEAN;
    case '?string?':
      return EdmType.STRING;
    default:
      return undefined;
  }
};
 
/**
 * Replace operators.
 * @ignore
 * @param {string} whereClause The text where to replace the operators.
 * @return {string} The string with the replaced operators.
 * @ignore
 */
TableQuery._replaceOperators = function (whereClause) {
  var encodedWhereClause = whereClause.replace(/ == /g, ' ' + QueryComparisons.EQUAL + ' ');
  encodedWhereClause = encodedWhereClause.replace(/ != /g, ' ' + QueryComparisons.NOT_EQUAL + ' ');
  encodedWhereClause = encodedWhereClause.replace(/ >= /g, ' ' + QueryComparisons.GREATER_THAN_OR_EQUAL + ' ');
  encodedWhereClause = encodedWhereClause.replace(/ > /g, ' ' + QueryComparisons.GREATER_THAN + ' ');
  encodedWhereClause = encodedWhereClause.replace(/ <= /g, ' ' + QueryComparisons.LESS_THAN_OR_EQUAL + ' ');
  encodedWhereClause = encodedWhereClause.replace(/ < /g, ' ' + QueryComparisons.LESS_THAN + ' ');
  encodedWhereClause = encodedWhereClause.replace(/ \&\& /g, ' ' + TableOperators.AND + ' ');
  encodedWhereClause = encodedWhereClause.replace(/ \|\| /g, ' ' + TableOperators.OR + ' ');
  encodedWhereClause = encodedWhereClause.replace(/!/g, TableOperators.NOT);
 
  return encodedWhereClause;
};
 
module.exports = TableQuery;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/tableservice.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/tableservice.js

Statements: 13.11% (51 / 389)      Branches: 0% (0 / 110)      Functions: 0% (0 / 80)      Lines: 13.97% (51 / 365)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392                                  1 1 1   1 1 1 1 1 1 1 1 1 1 1 1 1 1     1 1 1 1 1 1                                                             1                                         1                                             1                                                                                                       1                                               1                                                     1                                                       1                                                                                                                                                                             1                                                                                                           1                                                                                                                                 1                                                                       1                                               1                                                                                                                                   1                                                                                                                   1                                                                                           1                                                                                                                                                                                                                                                       1                                                                                                                                                                                                                                                                   1                                                                                                             1                                                 1                                                 1                                                 1                                                 1                                               1                                                     1                                                                                                                                                           1                                                                                                                                       1                                                                                                                                           1                                                           1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var util = require('util');
var extend = require('extend');
var _ = require('underscore');
 
var azureCommon = require('./../../common/common');
var azureutil = azureCommon.util;
var validate = azureCommon.validate;
var SR = azureCommon.SR;
var StorageServiceClient = azureCommon.StorageServiceClient;
var SharedKeyTable = require('./internal/sharedkeytable');
var RequestHandler = require('./internal/requesthandler');
var TableQuery = require('./tablequery');
var WebResource = azureCommon.WebResource;
var Constants = azureCommon.Constants;
var QueryStringConstants = Constants.QueryStringConstants;
var HeaderConstants = Constants.HeaderConstants;
var TableConstants = Constants.TableConstants;
var RequestLocationMode = Constants.RequestLocationMode;
 
// Models requires
var TableResult = require('./models/tableresult');
var entityResult = require('./models/entityresult');
var BatchResult = require('./models/batchresult');
var ServiceStatsParser = azureCommon.ServiceStatsParser;
var AclResult = azureCommon.AclResult;
var TableUtilities = require('./tableutilities');
 
/**
* Creates a new TableService object.
* If no connection string or storageaccount and storageaccesskey are provided,
* the AZURE_STORAGE_CONNECTION_STRING or AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables will be used.
* @class
* The TableService object allows you to peform management operations with the Microsoft Azure Table Service.
* The Table Service stores data in rows of key-value pairs. A table is composed of multiple rows, and each row
* contains key-value pairs. There is no schema, so each row in a table may store a different set of keys.
*
* For more information on the Table Service, as well as task focused information on using it from a Node.js application, see
* [How to Use the Table Service from Node.js](http://azure.microsoft.com/en-us/documentation/articles/storage-nodejs-how-to-use-table-storage/).
* The following defaults can be set on the Table service.
* defaultTimeoutIntervalInMs                          The default timeout interval, in milliseconds, to use for request made via the Table service.
* defaultClientRequestTimeoutInMs                     The default timeout of client requests, in milliseconds, to use for the request made via the Table service.
* defaultMaximumExecutionTimeInMs                     The default maximum execution time across all potential retries, for requests made via the Table service.
* defaultLocationMode                                 The default location mode for requests made via the Table service.
* defaultPayloadFormat                                The default payload format for requests made via the Table service.
* useNagleAlgorithm                                   Determines whether the Nagle algorithm is used for requests made via the Table service.; true to use the  
*                                                     Nagle algorithm; otherwise, false. The default value is false.
* @constructor
* @extends {StorageServiceClient}
*
* @param {string} [storageAccountOrConnectionString]  The storage account or the connection string.
* @param {string} [storageAccessKey]                  The storage access key.
* @param {string|object} [host]                       The host address. To define primary only, pass a string. 
*                                                     Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host.
* @param {string} [sasToken]                          The Shared Access Signature token.
* @param {string} [endpointSuffix]                    The endpoint suffix.
*/
function TableService(storageAccountOrConnectionString, storageAccessKey, host, sasToken, endpointSuffix) {
  var storageServiceSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey, host, sasToken, endpointSuffix);
 
  TableService['super_'].call(this,
    storageServiceSettings._name,
    storageServiceSettings._key,
    storageServiceSettings._tableEndpoint,
    storageServiceSettings._usePathStyleUri,
    storageServiceSettings._sasToken);
 
  if (this.anonymous) {
    throw new Error(SR.ANONYMOUS_ACCESS_BLOBSERVICE_ONLY);
  }
 
  if(this.storageAccount && this.storageAccessKey) {
    this.storageCredentials = new SharedKeyTable(this.storageAccount, this.storageAccessKey, this.usePathStyleUri);
  }
 
  this.defaultPayloadFormat = TableUtilities.PayloadFormat.MINIMAL_METADATA;
}
 
util.inherits(TableService, StorageServiceClient);
 
// Table service methods
 
/**
* Gets the service stats for a storage account’s Table service.
*
* @this {TableService}
* @param {object}         [options]                                       The request options.
* @param {LocationMode}   [options.locationMode]                          Specifies the location mode used to decide which location the request should be sent to. 
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}            [options.timeoutIntervalInMs]                   The server timeout interval, in milliseconds, to use for the request.
* @param {int}            [options.clientRequestTimeoutInMs]              The timeout of client requests, in milliseconds, to use for the request.
* @param {int}            [options.maximumExecutionTimeInMs]              The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}         [options.clientRequestId]                       A string that represents the client request ID with a 1KB character limit.
* @param {bool}           [options.useNagleAlgorithm]                     Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                         The default value is false.
* @param {errorOrResult}  callback                                        `error` will contain information if an error occurs; 
*                                                                         otherwise `[result]{@link ServiceStats}` will contain the stats.
*                                                                         `response` will contain information related to this operation.
*/
TableService.prototype.getServiceStats = function (optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('getServiceStats', function (v) {
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
 
  var webResource = WebResource.get()
    .withQueryOption(QueryStringConstants.COMP, 'stats')
    .withQueryOption(QueryStringConstants.RESTYPE, 'service');
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.serviceStatsResult = null;
    if (!responseObject.error) {
      responseObject.serviceStatsResult = ServiceStatsParser.parse(responseObject.response.body.StorageServiceStats);
    }
 
    // function to be called after all filters
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.serviceStatsResult, returnObject.response);
    };
 
    // call the first filter
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Gets the properties of a storage account’s Table service, including Azure Storage Analytics.
*
* @this {TableService}
* @param {object}             [options]                                    The request options.
* @param {LocationMode}       [options.locationMode]                       Specifies the location mode used to decide which location the request should be sent to. 
*                                                                          Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]           The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]           The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                          The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                          execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                    A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                  Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                          The default value is false.
* @param {errorOrResult}  callback                                         `error` will contain information if an error occurs; 
*                                                                          otherwise `[result]{@link ServiceProperties}` will contain the properties.
*                                                                         `response` will contain information related to this operation.
*/
TableService.prototype.getServiceProperties = function (optionsOrCallback, callback) {
  return this.getAccountServiceProperties(optionsOrCallback, callback);
};
 
/**
* Sets the properties of a storage account’s Table service, including Azure Storage Analytics.
* You can also use this operation to set the default request version for all incoming requests that do not have a version specified.
*
* @this {TableService}
* @param {object}             serviceProperties                            The service properties.
* @param {object}             [options]                                    The request options.
* @param {LocationMode}       [options.locationMode]                       Specifies the location mode used to decide which location the request should be sent to. 
*                                                                          Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]           The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]           The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                          The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                          execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                    A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                  Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                          The default value is false.
* @param {errorOrResponse}  callback                                       `error` will contain information if an error occurs; 
*                                                                          `response` will contain information related to this operation.
*/
TableService.prototype.setServiceProperties = function (serviceProperties, optionsOrCallback, callback) {
  return this.setAccountServiceProperties(serviceProperties, optionsOrCallback, callback);
};
 
/**
* Lists a segment containing a collection of table items under the specified account.
*
* @this {TableService}
* @param {object}             currentToken                                      A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {object}             [options]                                         The create options or callback function.
* @param {int}                [options.maxResults]                              Specifies the maximum number of tables to return per call to Azure ServiceClient. 
* @param {LocationMode}       [options.locationMode]                            Specifies the location mode used to decide which location the request should be sent to. 
*                                                                               Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                     The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]                The timeout of client requests, in milliseconds, to use for the request.
* @param {string}             [options.payloadFormat]                           The payload format to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]                The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                               The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                               execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                         A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                       Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                               The default value is false.
* @param {errorOrResult}  callback                                              `error` will contain information if an error occurs; 
*                                                                               otherwise `result` will contain `entries` and `continuationToken`. 
*                                                                               `entries`  gives a list of tables and the `continuationToken` is used for the next listing operation.
*                                                                               `response` will contain information related to this operation.
*/
TableService.prototype.listTablesSegmented = function (currentToken, optionsOrCallback, callback) {
  this.listTablesSegmentedWithPrefix(null /* prefix */, currentToken, optionsOrCallback, callback);
};
 
/**
* Lists a segment containing a collection of table items under the specified account.
*
* @this {TableService}
* @param {string}             prefix                                            The prefix of the table name.
* @param {object}             currentToken                                      A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {object}             [options]                                         The create options or callback function.
* @param {int}                [options.maxResults]                              Specifies the maximum number of tables to return per call to Azure ServiceClient. 
* @param {LocationMode}       [options.locationMode]                            Specifies the location mode used to decide which location the request should be sent to. 
*                                                                               Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                     The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]                The timeout of client requests, in milliseconds, to use for the request.
* @param {string}             [options.payloadFormat]                           The payload format to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]                The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                               The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                               execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                         A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                       Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                               The default value is false.
* @param {errorOrResult}  callback                                              `error` will contain information if an error occurs; 
*                                                                               otherwise `result` will contain `entries` and `continuationToken`. 
*                                                                               `entries`  gives a list of tables and the `continuationToken` is used for the next listing operation.
*                                                                               `response` will contain information related to this operation.
*/
TableService.prototype.listTablesSegmentedWithPrefix = function (prefix, currentToken, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('listTables', function (v) {
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  options.payloadFormat = options.payloadFormat || this.defaultPayloadFormat;
 
  var webResource = WebResource.get(TableConstants.TABLE_SERVICE_TABLE_NAME);
  RequestHandler.setTableRequestHeadersAndBody(webResource, null, options.payloadFormat);
 
  if(!azureutil.objectIsNull(currentToken)) {
    webResource.withQueryOption(TableConstants.NEXT_TABLE_NAME, currentToken.nextTableName);
  }
 
  if(!azureutil.objectIsNull(prefix)) {
    var query = new TableQuery()
      .where(TableConstants.TABLE_NAME + ' >= ?', prefix)
      .and(TableConstants.TABLE_NAME + ' < ?', prefix + '{');
    
    webResource.withQueryOption(QueryStringConstants.FILTER, query.toQueryObject().$filter);
  }
 
  if(!azureutil.objectIsNull(options.maxResults)) {
    var query = new TableQuery().top(options.maxResults);
    webResource.withQueryOption(QueryStringConstants.TOP, query.toQueryObject().$top);
  }
 
  options.requestLocationMode = azureutil.getNextListingLocationMode(currentToken);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.listTablesResult = null;
 
    if (!responseObject.error) {
      responseObject.listTablesResult = {
        entries: null,
        continuationToken: null
      };
      responseObject.listTablesResult.entries = TableResult.parse(responseObject.response);
 
      if (responseObject.response.headers[TableConstants.CONTINUATION_NEXT_TABLE_NAME] &&
      !azureutil.objectIsEmpty(responseObject.response.headers[TableConstants.CONTINUATION_NEXT_TABLE_NAME])) {
        responseObject.listTablesResult.continuationToken = {
          nextTableName: null,
          targetLocation: null
        };
 
        responseObject.listTablesResult.continuationToken.nextTableName = responseObject.response.headers[TableConstants.CONTINUATION_NEXT_TABLE_NAME];
        responseObject.listTablesResult.continuationToken.targetLocation = responseObject.targetLocation;
      }
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.listTablesResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
// Table Methods
 
/**
* Gets the table's ACL.
*
* @this {TableService}
* @param {string}             table                                        The table name.
* @param {object}             [options]                                    The request options.
* @param {LocationMode}       [options.locationMode]                       Specifies the location mode used to decide which location the request should be sent to. 
*                                                                          Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]           The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]           The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                          The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                          execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                    A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                  Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                          The default value is false.
* @param {errorOrResult}  callback                                         `error` will contain information if an error occurs; 
*                                                                          otherwise `result` will contain the ACL information for the table. See `[AccessPolicy]{@link AccessPolicy}` for detailed information.
*                                                                          `response` will contain information related to this operation.
*/
TableService.prototype.getTableAcl = function (table, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('getTableAcl', function (v) {
    v.string(table, 'table');
    v.tableNameIsValid(table);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
 
  var webResource = WebResource.get(table)
    .withQueryOption(QueryStringConstants.COMP, 'acl');
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.tableResult = null;
    if (!responseObject.error) {
      responseObject.tableResult = new TableResult(table);
      responseObject.tableResult.signedIdentifiers = AclResult.parse(responseObject.response.body);
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.tableResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Updates the table's ACL.
*
* @this {TableService}
* @param {string}                                 table                                        The table name.
* @param {Object.<string, AccessPolicy>}             signedIdentifiers                            The table ACL settings. See `[AccessPolicy]{@link AccessPolicy}` for detailed information.
* @param {object}                                 [options]                                    The request options.
* @param {LocationMode}                           [options.locationMode]                       Specifies the location mode used to decide which location the request should be sent to. 
*                                                                                              Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                                    [options.timeoutIntervalInMs]                The server timeout interval, in milliseconds, to use for the request.
* @param {int}                                    [options.clientRequestTimeoutInMs]           The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                                    [options.maximumExecutionTimeInMs]           The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                                              The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                                              execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}                                 [options.clientRequestId]                    A string that represents the client request ID with a 1KB character limit.
* @param {bool}                                   [options.useNagleAlgorithm]                  Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                                              The default value is false.
* @param {errorOrResult}                          callback                                     `error` will contain information if an error occurs; 
*                                                                                              otherwise `result` will contain information for the table.
*                                                                                              `response` will contain information related to this operation.
*/
TableService.prototype.setTableAcl = function (table, signedIdentifiers, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('setTableAcl', function (v) {
    v.string(table, 'table');
    v.tableNameIsValid(table);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
 
  var policies = null;
  if (signedIdentifiers) {
    if(_.isArray(signedIdentifiers)) {
      throw new TypeError(SR.INVALID_SIGNED_IDENTIFIERS);
    }
    policies = AclResult.serialize(signedIdentifiers);
  }
 
  var webResource = WebResource.put(table)
    .withQueryOption(QueryStringConstants.COMP, 'acl')
    .withHeader(HeaderConstants.CONTENT_LENGTH, !azureutil.objectIsNull(policies) ? Buffer.byteLength(policies) : 0)
    .withBody(policies);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.tableResult = null;
    if (!responseObject.error) {
 
      // SetTableAcl doesn't actually return anything in the response
      responseObject.tableResult = new TableResult(table);
      if (signedIdentifiers) {
        responseObject.tableResult.signedIdentifiers = signedIdentifiers;
      }
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.tableResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, webResource.body, options, processResponseCallback);
};
 
/**
* Retrieves a shared access signature token.
*
* @this {TableService}
* @param {string}                   table                                               The table name.
* @param {object}                   sharedAccessPolicy                                  The shared access policy.
* @param {string}                   [sharedAccessPolicy.Id]                             The signed identifier.
* @param {object}                   [sharedAccessPolicy.AccessPolicy.Permissions]       The permission type.
* @param {date|string}              [sharedAccessPolicy.AccessPolicy.Start]             The time at which the Shared Access Signature becomes valid (The UTC value will be used).
* @param {date|string}              [sharedAccessPolicy.AccessPolicy.Expiry]            The time at which the Shared Access Signature becomes expired (The UTC value will be used).
* @param {string}                   [sharedAccessPolicy.AccessPolicy.IPAddressOrRange]  An IP address or a range of IP addresses from which to accept requests. When specifying a range, note that the range is inclusive.
* @param {string}                   [sharedAccessPolicy.AccessPolicy.Protocols]         The protocols permitted for a request made with the account SAS. 
*                                                                                       Possible values are both HTTPS and HTTP (https,http) or HTTPS only (https). The default value is https,http.
* @param {string}                   [sharedAccessPolicy.AccessPolicy.StartPk]           The starting Partition Key for which the SAS will be valid.
* @param {string}                   [sharedAccessPolicy.AccessPolicy.EndPk]             The ending Partition Key for which the SAS will be valid.
* @param {string}                   [sharedAccessPolicy.AccessPolicy.StartRk]           The starting Row Key for which the SAS will be valid.
* @param {string}                   [sharedAccessPolicy.AccessPolicy.EndRk]             The ending Row Key for which the SAS will be valid.
* @return {object}                                                                      An object with the shared access signature.
*/
TableService.prototype.generateSharedAccessSignature = function (table, sharedAccessPolicy) {
  // check if the TableService is able to generate a shared access signature
  if (!this.storageCredentials || !this.storageCredentials.generateSignedQueryString) {
    throw new Error(SR.CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY);
  }
 
  validate.validateArgs('generateSharedAccessSignature', function (v) {
    v.string(table, 'table');
    v.tableNameIsValid(table);
    v.object(sharedAccessPolicy, 'sharedAccessPolicy');
  });
  
  var lowerCasedTableName = table.toLowerCase();
  return this.storageCredentials.generateSignedQueryString(Constants.ServiceType.Table, lowerCasedTableName, sharedAccessPolicy, null, { tableName: lowerCasedTableName });
};
 
/**
* Checks whether or not a table exists on the service.
*
* @this {TableService}
* @param {string}             table                                   The table name.
* @param {object}             [options]                               The request options.
* @param {LocationMode}       [options.locationMode]                  Specifies the location mode used to decide which location the request should be sent to. 
*                                                                     Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]           The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]      The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]      The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                     The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                     execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]               A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]             Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                     The default value is false.
* @param {errorOrResult}  callback                                    `error` will contain information if an error occurs; 
*                                                                     otherwise `result` will contain the table information including `exists` boolean member. 
*                                                                     `response` will contain information related to this operation.
*/
TableService.prototype.doesTableExist = function (table, optionsOrCallback, callback) {
  this._doesTableExist(table, false, optionsOrCallback, callback);
};
 
/**
* Creates a new table within a storage account.
*
* @this {TableService}
* @param {string}             table                                   The table name.
* @param {object}             [options]                               The request options.
* @param {LocationMode}       [options.locationMode]                  Specifies the location mode used to decide which location the request should be sent to. 
*                                                                     Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]           The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]      The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]      The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                     The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                     execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]               A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]             Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                     The default value is false.
* @param {errorOrResult}  callback                                    `error` will contain information if an error occurs; 
*                                                                     otherwise `result` will contain the new table information.
*                                                                     `response` will contain information related to this operation.
*/
TableService.prototype.createTable = function (table, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('createTable', function (v) {
    v.string(table, 'table');
    v.tableNameIsValid(table);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
 
  var tableDescriptor = TableResult.serialize(table);
 
  var webResource = WebResource.post('Tables')
    .withHeader(HeaderConstants.PREFER, HeaderConstants.PREFER_NO_CONTENT);
 
  RequestHandler.setTableRequestHeadersAndBody(webResource, tableDescriptor, this.defaultPayloadFormat);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.tableResponse = {};
    responseObject.tableResponse.isSuccessful = responseObject.error ? false : true;
    responseObject.tableResponse.statusCode = responseObject.response.statusCode;
    if (!responseObject.error) {
      responseObject.tableResponse.TableName = table;
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.tableResponse, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, webResource.body, options, processResponseCallback);
};
 
/**
* Creates a new table within a storage account if it does not exists.
*
* @this {TableService}
* @param {string}             table                                   The table name.
* @param {object}             [options]                               The request options.
* @param {LocationMode}       [options.locationMode]                  Specifies the location mode used to decide which location the request should be sent to. 
*                                                                     Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]           The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]      The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]      The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                     The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                     execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]               A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]             Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                     The default value is false.
* @param {errorOrResult}  callback                                    `error` will contain information if an error occurs; 
*                                                                     `result` will contain the table information including `created` boolean member
*                                                                     `response` will contain information related to this operation.
*
* @example
* var azure = require('azure-storage');
* var tableService = azure.createTableService();
* tableService.createTableIfNotExists('tasktable', function(error) {
*   if(!error) { 
*     // Table created or exists
*   }
* });
*/
TableService.prototype.createTableIfNotExists = function (table, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('createTableIfNotExists', function (v) {
    v.string(table, 'table');
    v.tableNameIsValid(table);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
 
  var self = this;
  self._doesTableExist(table, true, options, function(error, result, response) {
    var exists = result.exists;
    result.created = false;
    delete result.exists;
    
    if (error) {
      callback(error, result, response);
    } else if (exists) {
      response.isSuccessful = true;
      callback(error, result, response);
    } else {
      self.createTable(table, options, function(createError, createResult, response) {
        if (!createError) {
          createResult.created = true;
        }
        else if (createError && createError.statusCode === Constants.HttpConstants.HttpResponseCodes.Conflict && createError.code === Constants.TableErrorCodeStrings.TABLE_ALREADY_EXISTS) {
          createError = null;
          createResult.created = false;
          createResult.isSuccessful = true;
        }
        callback(createError, createResult, response);
      });
    }
  });
};
 
/**
* Deletes a table from a storage account.
*
* @this {TableService}
* @param {string}             table                                   The table name.
* @param {object}             [options]                               The request options.
* @param {LocationMode}       [options.locationMode]                  Specifies the location mode used to decide which location the request should be sent to. 
*                                                                     Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]           The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]      The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]      The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                     The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                     execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]               A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]             Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                     The default value is false.
* @param {errorOrResponse}  callback                                  `error` will contain information if an error occurs;
*                                                                     `response` will contain information related to this operation.
*/
TableService.prototype.deleteTable = function (table, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('deleteTable', function (v) {
    v.string(table, 'table');
    v.tableNameIsValid(table);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
 
  var webResource = WebResource.del('Tables(\'' + table + '\')');
  RequestHandler.setTableRequestHeadersAndBody(webResource, null, this.defaultPayloadFormat);
 
  var processResponseCallback = function (responseObject, next) {
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Deletes a table from a storage account, if it exists.
*
* @this {TableService}
* @param {string}             table                                   The table name.
* @param {object}             [options]                               The request options.
* @param {LocationMode}       [options.locationMode]                  Specifies the location mode used to decide which location the request should be sent to. 
*                                                                     Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]           The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]      The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]      The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                     The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                     execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]               A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]             Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                     The default value is false.
* @param {errorOrResult}  callback                                    `error` will contain information if an error occurs; 
*                                                                     `result` will be `true` if table was deleted, false otherwise
*                                                                     `response` will contain information related to this operation.
*/
TableService.prototype.deleteTableIfExists = function (table, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('deleteTableIfExists', function (v) {
    v.string(table, 'table');
    v.tableNameIsValid(table);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
 
  var self = this;
  self._doesTableExist(table, true, options, function(error, result, response) {
    if (error) {
      callback(error, result.exists, response);
    } else if (!result.exists) {
      response.isSuccessful = true;
      callback(error, false, response);
    } else {
      self.deleteTable(table, options, function(deleteError, deleteResponse) {
        var deleted;
        if (!deleteError) {
          deleted = true;
        } else if (deleteError && deleteError.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound && deleteError.code === Constants.StorageErrorCodeStrings.RESOURCE_NOT_FOUND) {
          deleted = false;
          deleteError = null;
          deleteResponse.isSuccessful = true;
        }
 
        callback(deleteError, deleted, deleteResponse);
      });
    }
  });
};
 
// Table Entity Methods
 
/**
* Queries data in a table. To retrieve a single entity by partition key and row key, use retrieve entity.
*
* @this {TableService}
* @param {string}             table                                                The table name.
* @param {TableQuery}         tableQuery                                           The query to perform. Use null, undefined, or new TableQuery() to get all of the entities in the table.
* @param {object}             currentToken                                         A continuation token returned by a previous listing operation. 
*                                                                                  Please use 'null' or 'undefined' if this is the first operation.
* @param {object}             [options]                                            The request options.
* @param {LocationMode}       [options.locationMode]                               Specifies the location mode used to decide which location the request should be sent to. 
*                                                                                  Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                        The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]                   The timeout of client requests, in milliseconds, to use for the request.
* @param {string}             [options.payloadFormat]                              The payload format to use for the request.
* @param {bool}               [options.autoResolveProperties]                      If true, guess at all property types.
* @param {int}                [options.maximumExecutionTimeInMs]                   The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                                  The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                                  execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                            A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                          Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                                  The default value is false.
* @param {Function(entity)} [options.entityResolver]                               The entity resolver. Given a single entity returned by the query, returns a modified object which is added to 
*                                                                                  the entities array.
* @param {TableService~propertyResolver}  [options.propertyResolver]               The property resolver. Given the partition key, row key, property name, property value,
*                                                                                  and the property Edm type if given by the service, returns the Edm type of the property.
* @param {TableService~queryResponse} callback                                     `error` will contain information if an error occurs; 
*                                                                                  otherwise `entities` will contain the entities returned by the query. 
*                                                                                  If more matching entities exist, and could not be returned,
*                                                                                  `queryResultContinuation` will contain a continuation token that can be used
*                                                                                  to retrieve the next set of results.
*                                                                                  `response` will contain information related to this operation.
*
* The logic for returning entity types can get complicated.  Here is the algorithm used:
* ```
* var propertyType;
*
* if (propertyResovler) {                      // If the caller provides a propertyResolver in the options, use it
*   propertyType = propertyResolver(partitionKey, rowKey, propertyName, propertyValue, propertyTypeFromService);
* } else if (propertyTypeFromService) {        // If the service provides us a property type, use it.  See below for an explanation of when this will and won't occur.
*   propertyType = propertyTypeFromService;
* } else if (autoResolveProperties) {          // If options.autoResolveProperties is set to true
*   if (javascript type is string) {           // See below for an explanation of how and why autoResolveProperties works as it does.
*     propertyType = 'Edm.String';
*   } else if (javascript type is boolean) {
*     propertyType = 'Edm.Boolean';
*   }
* }
*
* if (propertyType) {
*   // Set the property type on the property.
* } else {
*   // Property gets no EdmType. 
* }
* ```
* Notes:
* 
* * The service only provides a type if JsonFullMetadata or JsonMinimalMetadata is used, and if the type is Int64, Guid, Binary, or DateTime.
* * Explanation of autoResolveProperties:
*     * String gets correctly resolved to 'Edm.String'.
*     * Int64, Guid, Binary, and DateTime all get resolved to 'Edm.String.'  This only happens if JsonNoMetadata is used (otherwise the service will provide the propertyType in a prior step).
*     * Boolean gets correctly resolved to 'Edm.Boolean'.
*     * For both Int32 and Double, no type information is returned, even in the case of autoResolveProperties = true.  This is due to an
*          inability to distinguish between the two in certain cases.
*
* @example
* var azure = require('azure-storage');
* var tableService = azure.createTableService();
* // tasktable should already exist and have entities
* 
* // returns all entities in tasktable, and a continuation token for the next page of results if necessary
* tableService.queryEntities('tasktable', null, null \/*currentToken*\/, function(error, result) {
*   if(!error) { 
*     var entities = result.entities;
*     // do stuff with the returned entities if there are any
*   }
* });
* 
* // returns field1 and field2 of the entities in tasktable, and a continuation token for the next page of results if necessary
* var tableQuery = new TableQuery().select('field1', 'field2');
* tableService.queryEntities('tasktable', tableQuery, null \/*currentToken*\/, function(error, result) {
*   if(!error) { 
*     var entities = result.entities;
*     // do stuff with the returned entities if there are any
*   }
* });
*/
TableService.prototype.queryEntities = function (table, tableQuery, currentToken, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('queryEntities', function (v) {
    v.string(table, 'table');
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  options.payloadFormat = options.payloadFormat || this.defaultPayloadFormat;
 
  var webResource = WebResource.get(table);
  RequestHandler.setTableRequestHeadersAndBody(webResource, null, options.payloadFormat);
 
  if (tableQuery) {
    var queryString = tableQuery.toQueryObject();
    Object.keys(queryString).forEach(function (queryStringName) {
      webResource.withQueryOption(queryStringName, queryString[queryStringName]);
    });
  }
 
  if(!azureutil.objectIsNull(currentToken)) {
    webResource.withQueryOption(TableConstants.NEXT_PARTITION_KEY, currentToken.nextPartitionKey);
    webResource.withQueryOption(TableConstants.NEXT_ROW_KEY, currentToken.nextRowKey);
  }
 
  options.requestLocationMode = azureutil.getNextListingLocationMode(currentToken);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.queryEntitiesResult = null;
    if (!responseObject.error) {
      responseObject.queryEntitiesResult = {
        entries: null,
        continuationToken: null
      };
 
      // entries
      responseObject.queryEntitiesResult.entries = entityResult.parseQuery(responseObject.response, options.autoResolveProperties, options.propertyResolver, options.entityResolver);
 
      // continuation token
      var continuationToken = {
          nextPartitionKey: responseObject.response.headers[TableConstants.CONTINUATION_NEXT_PARTITION_KEY],
          nextRowKey: responseObject.response.headers[TableConstants.CONTINUATION_NEXT_ROW_KEY],
          targetLocation: responseObject.targetLocation
        };
 
      if (!azureutil.IsNullOrEmptyOrUndefinedOrWhiteSpace(continuationToken.nextPartitionKey)) {
        responseObject.queryEntitiesResult.continuationToken = continuationToken;
      }
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.queryEntitiesResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Retrieves an entity from a table.
*
* @this {TableService}
* @param {string}             table                                           The table name.
* @param {string}             partitionKey                                    The partition key.
* @param {string}             rowKey                                          The row key.
* @param {object}             [options]                                       The request options.
* @param {LocationMode}       [options.locationMode]                          Specifies the location mode used to decide which location the request should be sent to. 
*                                                                             Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                   The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]              The timeout of client requests, in milliseconds, to use for the request.
* @param {string}             [options.payloadFormat]                         The payload format to use for the request.
* @param {bool}               [options.autoResolveProperties]                 If true, guess at all property types.
* @param {int}                [options.maximumExecutionTimeInMs]              The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                             The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                             execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                       A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                     Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                             The default value is false.
* @param {TableService~propertyResolver}  [options.propertyResolver]          The property resolver. Given the partition key, row key, property name, property value,
*                                                                             and the property Edm type if given by the service, returns the Edm type of the property.
* @param {Function(entity)} [options.entityResolver]                          The entity resolver. Given the single entity returned by the query, returns a modified object.
* @param {errorOrResult}  callback                                            `error` will contain information if an error occurs; 
*                                                                             otherwise `result` will be the matching entity.
*                                                                             `response` will contain information related to this operation.
*
* The logic for returning entity types can get complicated.  Here is the algorithm used:
* ```
* var propertyType;
*
* if (propertyResovler) {                      // If the caller provides a propertyResolver in the options, use it
*   propertyType = propertyResolver(partitionKey, rowKey, propertyName, propertyValue, propertyTypeFromService);
* } else if (propertyTypeFromService) {        // If the service provides us a property type, use it.  See below for an explanation of when this will and won't occur.
*   propertyType = propertyTypeFromService;
* } else if (autoResolveProperties) {          // If options.autoResolveProperties is set to true
*   if (javascript type is string) {           // See below for an explanation of how and why autoResolveProperties works as it does.
*     propertyType = 'Edm.String';
*   } else if (javascript type is boolean) {
*     propertyType = 'Edm.Boolean';
*   }
* }
*
* if (propertyType) {
*   // Set the property type on the property.
* } else {
*   // Property gets no EdmType. 
* }
* ```
* Notes:
* 
* * The service only provides a type if JsonFullMetadata or JsonMinimalMetadata is used, and if the type is Int64, Guid, Binary, or DateTime.
* * Explanation of autoResolveProperties:
*     * String gets correctly resolved to 'Edm.String'.
*     * Int64, Guid, Binary, and DateTime all get resolved to 'Edm.String.'  This only happens if JsonNoMetadata is used (otherwise the service will provide the propertyType in a prior step).
*     * Boolean gets correctly resolved to 'Edm.Boolean'.
*     * For both Int32 and Double, no type information is returned, even in the case of autoResolveProperties = true.  This is due to an
*          inability to distinguish between the two in certain cases.
*
* @example
* var azure = require('azure-storage');
* var tableService = azure.createTableService();
* tableService.retrieveEntity('tasktable', 'tasksSeattle', '1', function(error, serverEntity) {
*   if(!error) {
*     // Entity available in serverEntity variable
*   }
* });
*/
TableService.prototype.retrieveEntity = function (table, partitionKey, rowKey, optionsOrCallback, callback) {
  var entityDescriptor = { PartitionKey: {_: partitionKey, $: 'Edm.String'},
    RowKey: {_: rowKey, $: 'Edm.String'},
  };
 
  validate.validateArgs('retrieveEntity', function (v) {
    v.stringAllowEmpty(partitionKey, 'partitionKey');
    v.stringAllowEmpty(rowKey, 'rowKey');
  });
 
  this._performEntityOperation(TableConstants.Operations.RETRIEVE, table, entityDescriptor, optionsOrCallback, callback);
};
 
/**
* Inserts a new entity into a table.
*
* @this {TableService}
* @param {string}             table                                           The table name.
* @param {object}             entityDescriptor                                The entity descriptor.
* @param {object}             [options]                                       The request options.
* @param {string}             [options.echoContent]                           Whether or not to return the entity upon a successful insert. Default to false.
* @param {string}             [options.payloadFormat]                         The payload format to use in the response, if options.echoContent is true.
* @param {LocationMode}       [options.locationMode]                          Specifies the location mode used to decide which location the request should be sent to. 
*                                                                             Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                   The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]              The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]              The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                             The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                             execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                       A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                     Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                             The default value is false.
* @param {TableService~propertyResolver}  [options.propertyResolver]          The property resolver. Only applied if echoContent is true. Given the partition key, row key, property name, 
*                                                                             property value, and the property Edm type if given by the service, returns the Edm type of the property.
* @param {Function(entity)} [options.entityResolver]                          The entity resolver. Only applied if echoContent is true. Given the single entity returned by the insert, returns 
*                                                                             a modified object.
* @param {errorOrResult}  callback                                            `error` will contain information if an error occurs; 
*                                                                             otherwise `result` will contain the entity information.
*                                                                             `response` will contain information related to this operation.
*
* @example
* var azure = require('azure-storage');
* var tableService = azure.createTableService();
* var task1 = {
*   PartitionKey : {'_': 'tasksSeattle', '$':'Edm.String'},
*   RowKey: {'_': '1', '$':'Edm.String'},
*   Description: {'_': 'Take out the trash', '$':'Edm.String'},
*   DueDate: {'_': new Date(2011, 12, 14, 12), '$':'Edm.DateTime'}
* };
* tableService.insertEntity('tasktable', task1, function(error) {
*   if(!error) {
*     // Entity inserted
*   }
* }); 
*/
TableService.prototype.insertEntity = function (table, entityDescriptor, optionsOrCallback, callback) {
  this._performEntityOperation(TableConstants.Operations.INSERT, table, entityDescriptor, optionsOrCallback, callback);
};
 
/**
* Inserts or updates a new entity into a table.
*
* @this {TableService}
* @param {string}             table                                   The table name.
* @param {object}             entityDescriptor                        The entity descriptor.
* @param {object}             [options]                               The request options.
* @param {LocationMode}       [options.locationMode]                  Specifies the location mode used to decide which location the request should be sent to. 
*                                                                     Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]           The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]      The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]      The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                     The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                     execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]               A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]             Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                     The default value is false.
* @param {errorOrResult}  callback                                    `error` will contain information if an error occurs; 
*                                                                     otherwise `result` will contain the entity information.
*                                                                     `response` will contain information related to this operation.
*/
TableService.prototype.insertOrReplaceEntity = function (table, entityDescriptor, optionsOrCallback, callback) {
  this._performEntityOperation(TableConstants.Operations.INSERT_OR_REPLACE, table, entityDescriptor, optionsOrCallback, callback);
};
 
/**
* Replaces an existing entity within a table. To replace conditionally based on etag, set entity['.metadata']['etag'].
*
* @this {TableService}
* @param {string}             table                                   The table name.
* @param {object}             entityDescriptor                        The entity descriptor.
* @param {object}             [options]                               The request options.
* @param {LocationMode}       [options.locationMode]                  Specifies the location mode used to decide which location the request should be sent to. 
*                                                                     Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]           The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]      The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]      The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                     The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                     execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]               A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]             Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                     The default value is false.
* @param {errorOrResult}  callback                                    `error` will contain information if an error occurs; 
*                                                                     otherwise `result` will contain the entity information.
*                                                                     `response` will contain information related to this operation.
*/
TableService.prototype.replaceEntity = function (table, entityDescriptor, optionsOrCallback, callback) {
  this._performEntityOperation(TableConstants.Operations.REPLACE, table, entityDescriptor, optionsOrCallback, callback);
};
 
/**
* Updates an existing entity within a table by merging new property values into the entity. To merge conditionally based on etag, set entity['.metadata']['etag'].
*
* @this {TableService}
* @param {string}             table                                   The table name.
* @param {object}             entityDescriptor                        The entity descriptor. 
* @param {object}             [options]                               The request options.
* @param {LocationMode}       [options.locationMode]                  Specifies the location mode used to decide which location the request should be sent to. 
*                                                                     Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]           The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]      The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]      The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                     The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                     execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]               A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]             Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                     The default value is false.
* @param {errorOrResult}  callback                                    `error` will contain information if an error occurs; 
*                                                                     otherwise `result` will contain the entity information.
*                                                                     response` will contain information related to this operation.
*/
TableService.prototype.mergeEntity = function (table, entityDescriptor, optionsOrCallback, callback) {
  this._performEntityOperation(TableConstants.Operations.MERGE, table, entityDescriptor, optionsOrCallback, callback);
};
 
/**
* Inserts or updates an existing entity within a table by merging new property values into the entity.
*
* @this {TableService}
* @param {string}             table                                   The table name.
* @param {object}             entityDescriptor                        The entity descriptor.
* @param {object}             [options]                               The request options.
* @param {LocationMode}       [options.locationMode]                  Specifies the location mode used to decide which location the request should be sent to. 
*                                                                     Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]           The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]      The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]      The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                     The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                     execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]               A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]             Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                     The default value is false.
* @param {errorOrResult}  callback                                    `error` will contain information if an error occurs; 
*                                                                     otherwise `result` will contain the entity information.
*                                                                     `response` will contain information related to this operation.
*/
TableService.prototype.insertOrMergeEntity = function (table, entityDescriptor, optionsOrCallback, callback) {
  this._performEntityOperation(TableConstants.Operations.INSERT_OR_MERGE, table, entityDescriptor, optionsOrCallback, callback);
};
 
/**
* Deletes an entity within a table. To delete conditionally based on etag, set entity['.metadata']['etag'].
*
* @this {TableService}
* @param {string}             table                                   The table name.
* @param {object}             entityDescriptor                        The entity descriptor.
* @param {object}             [options]                               The request options.
* @param {LocationMode}       [options.locationMode]                  Specifies the location mode used to decide which location the request should be sent to. 
*                                                                     Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]           The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]      The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]      The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                     The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                     execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]               A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]             Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                     The default value is false.
* @param {errorOrResponse}  callback                                  `error` will contain information if an error occurs; 
*                                                                     `response` will contain information related to this operation.
*/
TableService.prototype.deleteEntity = function (table, entityDescriptor, optionsOrCallback, callback) {
  this._performEntityOperation(TableConstants.Operations.DELETE, table, entityDescriptor, optionsOrCallback, callback);
};
 
/**
* Executes the operations in the batch.
*
* @this {TableService}
* @param {string}             table                                           The table name.
* @param {TableBatch}         batch                                           The table batch to execute.
* @param {object}             [options]                                       The create options or callback function.
* @param {LocationMode}       [options.locationMode]                          Specifies the location mode used to decide which location the request should be sent to. 
*                                                                             Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]                   The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]              The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]              The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                             The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                             execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                       A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                     Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                             The default value is false.
* @param {errorOrResult}  callback                                            `error` will contain information if an error occurs; 
*                                                                             otherwise `result` will contain responses for each operation executed in the batch;
*                                                                             `result.entity` will contain the entity information for each operation executed.
*                                                                             `result.response` will contain the response for each operations executed.
*                                                                             `response` will contain information related to this operation.
*/
TableService.prototype.executeBatch = function (table, batch, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('executeBatch', function (v) {
    v.string(table, 'table');
    v.tableNameIsValid(table);
    v.object(batch, 'batch');
    v.callback(callback);
  });
 
  if(!batch.hasOperations()) {
    throw new Error(SR.EMPTY_BATCH);
  }
 
  var options = extend(true, {}, userOptions);
 
  var batchResult = new BatchResult(this, table, batch.operations);
  var webResource = batchResult.constructWebResource();
 
  var body = batchResult.serialize();
  webResource.withBody(body);
  webResource.withHeader(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(body, 'utf8'));
 
  var processResponseCallback = function (responseObject, next) {
    var responseObjects = batchResult.parse(responseObject);
 
    var noError = true;
    // if the batch was unsuccesful, there will be a single response indicating the error
    if (responseObjects && responseObjects.length > 0) {
      responseObjects.forEach(function(item){
        if(noError && !item.response.isSuccessful){
          responseObject = item;
          noError = false;
        }
      });
    }
    
    if (noError) {
      responseObject.operationResponses = responseObjects;
    }
 
    var finalCallback = function (returnObject) {
      // perform final callback
      callback(returnObject.error, returnObject.operationResponses, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, webResource.body, options, processResponseCallback);
};
 
// Private methods
 
/**
* Checks whether or not a table exists on the service.
* @ignore
*
* @this {TableService}
* @param {string}             table                                   The table name.
* @param {string}             primaryOnly                             If true, the request will be executed against the primary storage location.
* @param {object}             [options]                               The request options.
* @param {LocationMode}       [options.locationMode]                  Specifies the location mode used to decide which location the request should be sent to. 
*                                                                     Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]           The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]      The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]      The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                     The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                     execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]               A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]             Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                     The default value is false.
* @param {Function(error, result, response)}  callback                `error` will contain information if an error occurs; 
*                                                                     otherwise `result` will contain
*                                                                     the table information including `exists` boolean member. 
*                                                                     `response` will contain information related to this operation.
*/
TableService.prototype._doesTableExist = function (table, primaryOnly, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('doesTableExist', function (v) {
    v.string(table, 'table');
    v.tableNameIsValid(table);
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  
  if(primaryOnly === false) {
    options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY;
  }
 
  var webResource = WebResource.get('Tables(\'' + table + '\')');
  webResource.withHeader(HeaderConstants.ACCEPT, this.defaultPayloadFormat);
 
  var processResponseCallback = function (responseObject, next) {
    responseObject.tableResult = {};
    responseObject.tableResult.isSuccessful = responseObject.error ? false : true;
    responseObject.tableResult.statusCode = responseObject.response === null || responseObject.response === undefined ? undefined : responseObject.response.statusCode;
    responseObject.tableResult.TableName = table;
    
    if(!responseObject.error){
      responseObject.tableResult.exists = true;
    } else if (responseObject.error && responseObject.error.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound) {
      responseObject.error = null;
      responseObject.tableResult.exists = false;
      responseObject.response.isSuccessful = true;
    }
 
    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.tableResult, returnObject.response);
    };
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, null, options, processResponseCallback);
};
 
/**
* Peforms a table operation.
*
* @this {TableService}
* @param {string}             operation                           The operation to perform.
* @param {string}             table                               The table name.
* @param {object}             entityDescriptor                    The entity descriptor.
* @param {object}             [options]                           The create options or callback function.
* @param {string}             [options.echoContent]               Whether or not to return the entity upon a successful insert. Default to false.
* @param {string}             [options.payloadFormat]             The payload format to use for the request.
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]           A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]         Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*                                                                 The default value is false.
* @param {errorOrResult}  callback                                `error` will contain information if an error occurs; 
*                                                                 otherwise `entity` will contain the entity information.
*                                                                 `response` will contain information related to this operation.
* @ignore
*/
TableService.prototype._performEntityOperation = function (operation, table, entityDescriptor, optionsOrCallback, callback) {
  var userOptions;
  azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
 
  validate.validateArgs('entityOperation', function (v) {
    v.string(table, 'table');
    v.tableNameIsValid(table);
    v.object(entityDescriptor, 'entityDescriptor');
 
    if(typeof entityDescriptor.PartitionKey !== 'string') {
      v.object(entityDescriptor.PartitionKey, 'entityDescriptor.PartitionKey');
      v.stringAllowEmpty(entityDescriptor.PartitionKey._, 'entityDescriptor.PartitionKey._');
    }
    
    if(typeof entityDescriptor.RowKey !== 'string') {
      v.object(entityDescriptor.RowKey, 'entityDescriptor.RowKey');
      v.stringAllowEmpty(entityDescriptor.RowKey._, 'entityDescriptor.RowKey._');
    }
    v.callback(callback);
  });
 
  var options = extend(true, {}, userOptions);
  options.payloadFormat = options.payloadFormat || this.defaultPayloadFormat;
 
  var webResource = RequestHandler.constructEntityWebResource(operation, table, entityDescriptor, options);
 
  var processResponseCallback = function (responseObject, next) {
    var finalCallback;
    if (operation === TableConstants.Operations.DELETE) {
      finalCallback = function (returnObject) {
        callback(returnObject.error, returnObject.response);
      };
    } else {
      responseObject.entityResponse = null;
      if (!responseObject.error) {
        responseObject.entityResponse = entityResult.parseEntity(responseObject.response, options.autoResolveProperties, options.propertyResolver, options.entityResolver);
      }
 
      finalCallback = function (returnObject) {
        callback(returnObject.error, returnObject.entityResponse, returnObject.response);
      };
    }
 
    next(responseObject, finalCallback);
  };
 
  this.performRequest(webResource, webResource.body, options, processResponseCallback);
};
 
/**
* Retrieves a table URL.
*
* @param {string}                   table                    The table name.
* @param {string}                   [sasToken]               The Shared Access Signature token.
* @param {boolean}                  [primary]                A boolean representing whether to use the primary or the secondary endpoint.
* @return {string}                                           The formatted URL string.
* @example
* var azure = require('azure-storage');
* var tableService = azure.createTableService();
* var sharedAccessPolicy = {
*   AccessPolicy: {
*     Permissions: azure.TableUtilities.SharedAccessPermissions.QUERY,
*     Start: startDate,
*     Expiry: expiryDate
*   },
* };
* 
* var sasToken = tableService.generateSharedAccessSignature(table, sharedAccessPolicy);
* var sasUrl = tableService.getUrl(table, sasToken);
*/
TableService.prototype.getUrl = function (table, sasToken, primary) {
  validate.validateArgs('getUrl', function (v) {
    v.string(table, 'table');
    v.tableNameIsValid(table);
  });
 
  return this._getUrl(table, sasToken, primary);
};
 
/**
* Given the partition key, row key, property name, property value,
* and the property Edm type if given by the service, returns the Edm type of the property.
* @typedef {function} TableService~propertyResolver
* @param {object} pk  The partition key.
* @param {object} rk  The row key.
* @param {string} name  The property name.
* @param {object} value The property value.
* @param {string} type  The EDM type.
*/
 
/** 
* Returns entities matched by a query.
* @callback TableService~queryResponse                                                                                
* @param {object} error                     If an error occurs, the error information.
* @param {object} entities                  The entities returned by the query.
* @param {object} queryResultContinuation   If more matching entities exist, and could not be returned,
*                                           a continuation token that can be used to retrieve more results.
* @param {object} response                  Information related to this operation.
*/
 
module.exports = TableService;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/tableutilities.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/tableutilities.js

Statements: 29.41% (5 / 17)      Branches: 0% (0 / 2)      Functions: 10% (1 / 10)      Lines: 29.41% (5 / 17)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155                                  1           1                                                                                                                                                                       1               1                                                                           1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Expose 'HeaderConstants'.
exports = module.exports;
 
/**
* Defines constants, enums, and utility functions for use with the Table service.
* @namespace TableUtilities
*/
var TableUtilities = {
  /**
  * Permission types.
  *
  * @const
  * @enum {string}
  */
  SharedAccessPermissions: {
    QUERY: 'r',
    ADD: 'a',
    UPDATE: 'u',
    DELETE: 'd'
  },
 
  /**
  * Payload Format.
  *
  * @const
  * @enum {string}
  */
  PayloadFormat: {
    FULL_METADATA: 'application/json;odata=fullmetadata',
    MINIMAL_METADATA: 'application/json;odata=minimalmetadata',
    NO_METADATA: 'application/json;odata=nometadata'
  },
 
  /**
  * Defines the set of Boolean operators for constructing queries.
  *
  * @const
  * @enum {string}
  */
  TableOperators: {
    AND: 'and',
    NOT: 'not',
    OR: 'or'
  },
 
  /**
  * Filter property comparison operators.
  *
  * @const
  * @enum {string}
  */
  QueryComparisons: {
    EQUAL: 'eq',
    NOT_EQUAL: 'ne',
    GREATER_THAN: 'gt',
    GREATER_THAN_OR_EQUAL: 'ge',
    LESS_THAN: 'lt',
    LESS_THAN_OR_EQUAL: 'le'
  },
 
  /**
  * Edm types.
  *
  * @const
  * @enum {string}
  */
  EdmType: {
    STRING: 'Edm.String',
    BINARY: 'Edm.Binary',
    INT64: 'Edm.Int64',
    INT32: 'Edm.Int32',
    DOUBLE: 'Edm.Double',
    DATETIME: 'Edm.DateTime',
    GUID: 'Edm.Guid',
    BOOLEAN: 'Edm.Boolean'
  },
 
  /**
  * A helper to create table entities.
  *
  * @example
  * var entGen = TableUtilities.entityGenerator;
  * var entity = {  PartitionKey: entGen.String('part2'),
  *        RowKey: entGen.String('row1'),
  *        boolValue: entGen.Boolean(true),
  *        intValue: entGen.Int32(42),
  *        dateValue: entGen.DateTime(new Date(Date.UTC(2011, 10, 25))),
  *       };
  */
  entityGenerator: (function()
  {
    var EntityProperty = function (value, type) {
        var entityProperty = { _:value};
        if (type) {
          entityProperty['$'] = type;
        }
        return entityProperty;
      };
 
      return {
      EntityProperty : EntityProperty,
      
      Int32 : function(value) {
        return new EntityProperty(value, 'Edm.Int32');
      },
 
      Int64 : function(value) {
        return new EntityProperty(value, 'Edm.Int64');
      },
 
      Binary : function(value) {
        return new EntityProperty(value, 'Edm.Binary');
      },
 
      Boolean : function(value) {
        return new EntityProperty(value, 'Edm.Boolean');
      },
 
      String : function(value) {
        return new EntityProperty(value, 'Edm.String');
      },
 
      Guid : function(value) {
        return new EntityProperty(value, 'Edm.Guid');
      },
 
      Double : function(value) {
        return new EntityProperty(value, 'Edm.Double');
      },
 
      DateTime : function(value) {
        return new EntityProperty(value, 'Edm.DateTime');
      }
    };
  })()
};
 
module.exports = TableUtilities;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/internal/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/internal/

Statements: 21.07% (51 / 242)      Branches: 0% (0 / 164)      Functions: 0% (0 / 18)      Lines: 21.07% (51 / 242)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/internal/
File Statements Branches Functions Lines
edmhandler.js 17.33% (13 / 75) 0% (0 / 75) 0% (0 / 5) 17.33% (13 / 75)
odatahandler.js 15.91% (14 / 88) 0% (0 / 46) 0% (0 / 6) 15.91% (14 / 88)
requesthandler.js 24% (12 / 50) 0% (0 / 37) 0% (0 / 3) 24% (12 / 50)
sharedkeytable.js 41.38% (12 / 29) 0% (0 / 6) 0% (0 / 4) 41.38% (12 / 29)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/internal/edmhandler.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/internal/edmhandler.js

Statements: 17.33% (13 / 75)      Branches: 0% (0 / 75)      Functions: 0% (0 / 5)      Lines: 17.33% (13 / 75)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198                                1 1 1   1 1 1   1 1               1                                                           1                                                                               1                                                                                   1                                                     1                                                  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var _ = require('underscore');
var util = require('util');
var guid = require('node-uuid');
 
var azureCommon = require('./../../../common/common');
var azureutil = azureCommon.util;
var SR = azureCommon.SR;
 
var TableUtilities = require('../tableutilities');
var EdmType = TableUtilities.EdmType;
 
/**
* Get the Edm type of an object.
*
* @param {object} value A typed instance.
* @return {string} The Edm type.
*/
exports.propertyType = function (value, guessNumberType) {
  if (_.isNumber(value)) {
    if (guessNumberType) {
      if (azureutil.objectIsInt(value)) {
        return 'Edm.Int32';
      } else {
        return 'Edm.Double';
      }
    } else {
      return null;
    }
  } else if (_.isBoolean(value)) {
    return 'Edm.Boolean';
  } else if (_.isDate(value)) {
    return 'Edm.DateTime';
  } else {
    return 'Edm.String';
  }
};
 
/**
* Convert a JSON value from over the wire into the correct EDM type.
* 
* Note that Int64, is remaining a string.  Converting it to a Number would lose precision.
* Int32, Boolean, and Double should already be the correct non-string types
*
* @param {string} type  The type of the value as it appears in the type attribute.
* @param value The value in JSON format.
* @return {object} The unserialized value.
*/
exports.deserializeValueFromJson = function (type, value) {
  if (type) {
    switch (type) {
      case EdmType.BINARY:
        return new Buffer(value, 'base64');
      case EdmType.DATETIME:
        return new Date(value);
      case EdmType.GUID:
        return value;
      case EdmType.DOUBLE:
        // Account for Infinity and NaN:
        if (typeof value !== 'number') {
          return parseFloat(value);
        }
        return value;
      case EdmType.INT32:
      case EdmType.INT64:
      case EdmType.STRING:
      case EdmType.BOOLEAN:
        return value;
      default:
        throw new Error(util.format(SR.TYPE_NOT_SUPPORTED, type));
    }
  } else {
    return value;
  }
};
 
/**
* Convert a raw EdmType value into the JSON value expected to be sent over the wire.
*
* TODO: validate correct input types?
* Expects Edm.Int64 and Edm.String to be string, Edm.Double and Edm.Int32 to be Number,
* Edm.Guid to be an array or buffer compatible with Node.uuid, Edm.Binary to be a Node Buffer, Edm.DateTime to be a Date,
* and Edm.Boolean to be a boolean.
*
* @param {string} type  The type of the value as it will appear in the type attribute.
* @param {string} value The value
* @return {object} The serialized value.
*/
exports.serializeValue = function (type, value) {
  switch (type) {
    case EdmType.BINARY:
      if (Buffer.isBuffer(value)) {
        return value.toString('base64');
      }
      return value;
    case EdmType.DATETIME:
      if (_.isDate(value)) {
        return value.toISOString();
      }
      return value;
    case EdmType.GUID:
      if (Buffer.isBuffer(value) || _.isArray(value)) {
        return guid.unparse(value);
      }
      return value;
    case EdmType.INT64:
    case EdmType.DOUBLE:
      return value.toString();
    case EdmType.INT32:
      if (value === Number.POSITIVE_INFINITY) {
        return 'Infinity';
      }
      if (value === Number.NEGATIVE_INFINITY) {
        return '-Infinity';
      }
      if (azureutil.objectIsNaN(value)) {
        return 'NaN';
      }
      return value;
    case EdmType.STRING:
    case EdmType.BOOLEAN:
      return value;
    default:
      throw new Error(SR.TYPE_NOT_SUPPORTED + type);
  }
};
 
/*
* Determines if a type annotation is required for the input type when sending JSON data to the service. 
*/
exports.isTypeRequired = function(type, value) {
  switch (type) {
  case EdmType.BINARY:
  case EdmType.INT64:
  case EdmType.DATETIME:
  case EdmType.GUID:
  case EdmType.DOUBLE:
    return true;
  case EdmType.INT32:
    if (typeof value !== 'number' || value === Number.POSITIVE_INFINITY || value === Number.NEGATIVE_INFINITY || (azureutil.objectIsNaN(value))) {
      return true;
    }
    return false;
  case EdmType.STRING:
  case EdmType.BOOLEAN:
    return false;
  default:
    throw new Error(util.format(SR.TYPE_NOT_SUPPORTED, type));
  }
};
 
/**
* Serializes value into proper value to be used in odata query value.
*
* @param {object} value The value to be serialized.
* @return {string} The serialized value.
*/
exports.serializeQueryValue = function (value, type) {
  var edmType = type || exports.propertyType(value, true);
  switch (edmType) {
    case EdmType.INT32:
      return value.toString();
    case EdmType.BOOLEAN:
      return value ? 'true' : 'false';
    case EdmType.DOUBLE:
      return value.toString();
    case EdmType.INT64:
      return value.toString() + 'L';
    case EdmType.DATETIME:
      if(_.isDate(value)) {
        var dateTimeString = value.toISOString();
        return 'datetime\'' + dateTimeString + '\'';
      }
      throw new Error(util.format(SR.INVALID_EDM_TYPE, value, type));
    case EdmType.GUID:
      return 'guid\'' + value.toString() + '\'';
    case EdmType.BINARY:
      return 'X\'' + value.toString('hex') + '\'';
    default:
      return '\'' + value.toString().replace(/'/g, '\'\'') + '\'';
  }   
};
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/internal/odatahandler.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/internal/odatahandler.js

Statements: 15.91% (14 / 88)      Branches: 0% (0 / 46)      Functions: 0% (0 / 6)      Lines: 15.91% (14 / 88)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219                                  1   1 1 1 1 1   1 1   1           1 1                                                                                                                                             1                                                               1                               1                                                                                                                                
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var util = require('util');
 
var azureCommon = require('./../../../common/common');
var azureutil = azureCommon.util;
var SR = azureCommon.SR;
var Constants = azureCommon.Constants;
var edmHandler = require('./edmhandler');
 
var prefixLength = Constants.TableConstants.ODATA_PREFIX.length;
var suffixLength = Constants.TableConstants.ODATA_TYPE_SUFFIX.length;
 
exports = module.exports;
 
/* Serialize an entity to an Odata (Json based) payload
* Input must be in the following format:
* { stringValue: { '$': 'Edm.String', '_': 'my string' }, myInt: { '$': 'Edm.Int32', '_': 3 } }
*/
exports.serializeJson = function (entity) {
  function normalizeEntityProperty(property) {
    if(azureutil.objectIsNull(property)) {
      return { _: property };
    }
 
    if (typeof property === 'object' && property.hasOwnProperty(Constants.TableConstants.ODATA_VALUE_MARKER)) {
      return property;
    }
 
    var result = { _: property };
    result[Constants.TableConstants.ODATA_TYPE_MARKER] = edmHandler.propertyType(property, true);
 
    return result;
  }
 
  var result = {};
  for (var propName in entity) {
    // ignore if .metadata or null or undefined
    if (propName !== Constants.TableConstants.ODATA_METADATA_MARKER) {
      var property = normalizeEntityProperty(entity[propName]);
      if (!azureutil.objectIsNull(property[Constants.TableConstants.ODATA_VALUE_MARKER])) {
        var value = property[Constants.TableConstants.ODATA_VALUE_MARKER];
        var type = property[Constants.TableConstants.ODATA_TYPE_MARKER];
 
        if (type === undefined) {
          type = edmHandler.propertyType(value, true);
        }
 
        result[propName] = edmHandler.serializeValue(type, value);
        if (edmHandler.isTypeRequired(type, value)) {
          result[propName + Constants.TableConstants.ODATA_TYPE_SUFFIX] = type;
        }
      }
    } 
  }
 
  var replacer = function(key, value) {
    if (value === Number.POSITIVE_INFINITY) {
      return 'Infinity';
    }
    if (value === Number.NEGATIVE_INFINITY) {
      return '-Infinity';
    }
    if (azureutil.objectIsNaN(value)) {
      return 'NaN';
    }
    return value;
  };
  
  return JSON.stringify(result, replacer);
};
 
/*
Input: The body of the HTTP response from the server from a table list as JSON (responseObject.response.body).
 
Return:
This will return an array in the following format:
 
[
  tableName1,
  tableName2
]
 
For example,
 
[
  myTable1,
  myTable2
]
 
*/
exports.parseJsonTables = function (response) {
  var result = [];
 
  if (response.value) {
    for (var i = 0; i < response.value.length; i++) {
      var entity = response.value[i].TableName;
      result.push(entity);
    }
  }
 
  return result;
};
 
/*
Input: The body of the HTTP response from the server from a table query as JSON (responseObject.response.body).
 
Return:
This will return an array in the following format:
 
[
  {{ '$': edmHandler1, '_': value1}, { '$': edmHandler2, '_': value2}, { '$': edmHandler3, '_': value3}},
  {{ '$': edmHandler4, '_': value4}, { '$': edmHandler5, '_': value5}, { '$': edmHandler6, '_': value6}}
]
 
For example,
 
[
  {{ '$': Edm.Int32, '_': 42}, { '$': Edm.String, '_': 'sample string'}, { '$': Edm.Boolean, '_': false}},
  {{ '$': Edm.Int64, '_': 42}, { '$': Edm.String, '_': 'sample string 2'}, { '$': Edm.Boolean, '_': true}}
]
 
*/
exports.parseJsonEntities = function (response, autoResolveProperties, propertyResolver, entityResolver) {
  if (!response.value) {
    return [exports.parseJsonSingleEntity(response, autoResolveProperties, propertyResolver, entityResolver)];
  } else {
    var result = [];
 
    for (var i = 0; i < response.value.length; i++) {
      var rawEntity = response.value[i];
      var entity = exports.parseJsonSingleEntity(rawEntity, autoResolveProperties, propertyResolver, entityResolver);
      result.push(entity);
    }
 
    return result;  
  }
};
 
exports.parseJsonSingleEntity = function(rawEntity, autoResolveProperties, propertyResolver, entityResolver) {
  var rawEntityProperties = {};
  var entityPropertyTypes = {PartitionKey: 'Edm.String', RowKey: 'Edm.String', Timestamp: 'Edm.DateTime'};
  var odataMetadata = {};
 
  // parse properties
  for (var entityPropertyName in rawEntity) {
    if (azureutil.stringStartsWith(entityPropertyName, Constants.TableConstants.ODATA_PREFIX)) {
      odataMetadata[entityPropertyName.slice(prefixLength)] = rawEntity[entityPropertyName];
    } else if (azureutil.stringEndsWith(entityPropertyName, Constants.TableConstants.ODATA_TYPE_SUFFIX)) {
      entityPropertyTypes[entityPropertyName.slice(0, entityPropertyName.length - suffixLength)] = rawEntity[entityPropertyName];
    } else {
      rawEntityProperties[entityPropertyName] = rawEntity[entityPropertyName];
    }
  }
 
  // make sure etag is set
  if (!odataMetadata.etag && rawEntityProperties.Timestamp) {
    var timestampString = new Buffer(rawEntityProperties.Timestamp).toString();
    odataMetadata.etag = 'W/"datetime\'' + timestampString + '\'"';
  }
 
  var entity = {};
  for (var entityPropertyName in rawEntityProperties) {
    if (rawEntityProperties.hasOwnProperty(entityPropertyName)) {
      // set the type, if given in the response
      var entityPropertyType = entityPropertyTypes[entityPropertyName];
      entity[entityPropertyName] = {};  
 
      // use the given property resolver if present, otherwise infer type if undefined
      if (propertyResolver) {
        // partition key, row key, name, value, type if present
        entityPropertyType = propertyResolver(rawEntityProperties.PartitionKey, rawEntityProperties.RowKey, entityPropertyName, rawEntityProperties[entityPropertyName], entityPropertyType);
      }
      if (!entityPropertyType && autoResolveProperties) {
        entityPropertyType = edmHandler.propertyType(rawEntityProperties[entityPropertyName], false);
      } 
 
      if (entityPropertyType) {
        entity[entityPropertyName][Constants.TableConstants.ODATA_TYPE_MARKER] = entityPropertyType;
      } 
 
      try {
        entity[entityPropertyName][Constants.TableConstants.ODATA_VALUE_MARKER] = edmHandler.deserializeValueFromJson(entityPropertyType, rawEntityProperties[entityPropertyName]);
      } catch (err) {
        if (propertyResolver) {
          // if a property resolver was used and the type is invalid, throw an appropriate error
          throw new Error(util.format(SR.INVALID_PROPERTY_RESOLVER, entityPropertyName, entityPropertyType, rawEntityProperties[entityPropertyName]));
        } else {
          throw err;
        }
      }
    }
  }
 
  entity[Constants.TableConstants.ODATA_METADATA_MARKER] = odataMetadata;
 
  if (entityResolver) {
    entity = entityResolver(entity);
  }
 
  return entity;
};
 
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/internal/requesthandler.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/internal/requesthandler.js

Statements: 24% (12 / 50)      Branches: 0% (0 / 37)      Functions: 0% (0 / 3)      Lines: 24% (12 / 50)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136                                1 1 1 1 1 1 1 1   1                   1                                                                   1                                                                                                               1                    
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
var util = require('util');
var azureCommon = require('./../../../common/common');
var WebResource = azureCommon.WebResource;
var SR = azureCommon.SR;
var Constants = azureCommon.Constants;
var HeaderConstants = Constants.HeaderConstants;
var TableConstants = Constants.TableConstants;
var entityResult = require('../models/entityresult');
 
exports = module.exports;
 
/**
* Retrieves the entity path from the table name and an entity descriptor.
* @ignore
*
* @param {string}   table         The table name.
* @param {object}   entity        The entity descriptor.
* @return {string} The entity path.
*/
function getEntityPath (tableName, partitionKey, rowKey) {
  var path = '/' + tableName;
 
  if (typeof (partitionKey) === 'string' && typeof (rowKey) === 'string') {
    // Escape single quotes according to OData Protocol Specification: "single quotes within string literals are represented as two consecutive single quotes".
    partitionKey = partitionKey.replace(/'/g, '\'\'');
    rowKey = rowKey.replace(/'/g, '\'\'');
    path = path + '(PartitionKey=\'' + encodeURIComponent(partitionKey.toString('utf8')) + '\',RowKey=\'' + encodeURIComponent(rowKey.toString('utf8')) + '\')';
  } else {
    throw new Error(SR.INCORRECT_ENTITY_KEYS);
  }
 
  return path;
}
 
/**
* Constructs the web resource for a table operation.
*
* @param {string}             operation                           The operation to perform.
* @param {string}             table                               The table name.
* @param {object}             entityDescriptor                    The entity descriptor.
* @param {object}             [options]                           The create options or callback function.
* @param {boolean}            [options.checkEtag]                 Boolean value indicating weather the etag should be matched or not.
* @param {string}             [options.echoContent]               Whether or not to return the entity upon a successful insert. Default to false.
* @param {string}             [options.payloadFormat]             The payload format to use for the request.
* @param {LocationMode}       [options.locationMode]              Specifies the location mode used to decide which location the request should be sent to. 
*                                                                 Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.timeoutIntervalInMs]       The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.clientRequestTimeoutInMs]  The timeout of client requests, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]  The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                 The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                 execution time is checked intermittently while performing requests, and before executing retries.
* @return {webResource}
*/
exports.constructEntityWebResource = function (operation, table, entityDescriptor, options) {
  var webResource = null;
  if (operation === TableConstants.Operations.INSERT) {
    webResource = WebResource.post(table)
      .withHeader(HeaderConstants.PREFER, options.echoContent ? HeaderConstants.PREFER_CONTENT : HeaderConstants.PREFER_NO_CONTENT);
  } else {
    var partitionKey;
    var rowKey;
 
    if (typeof (entityDescriptor.PartitionKey) === 'string') {
      partitionKey = entityDescriptor.PartitionKey;
    } else {
      partitionKey = entityDescriptor.PartitionKey[TableConstants.ODATA_VALUE_MARKER];
    }
 
    if (typeof (entityDescriptor.RowKey) === 'string') {
      rowKey = entityDescriptor.RowKey;
    } else {
      rowKey = entityDescriptor.RowKey[TableConstants.ODATA_VALUE_MARKER];
    }
 
    var path = getEntityPath(table, partitionKey, rowKey);
 
    if (operation === TableConstants.Operations.DELETE) {
      webResource = WebResource.del(path);
    } else if (operation === TableConstants.Operations.MERGE || operation === TableConstants.Operations.INSERT_OR_MERGE) {
      webResource = WebResource.merge(path);
    } else if (operation === TableConstants.Operations.REPLACE || operation === TableConstants.Operations.INSERT_OR_REPLACE) {
      webResource = WebResource.put(path);
    } else if (operation === TableConstants.Operations.RETRIEVE) {
      webResource = WebResource.get(path);
    } else {
      throw new Error(util.format(SR.INVALID_TABLE_OPERATION, operation));
    }
  }
 
  if (operation === TableConstants.Operations.DELETE || operation === TableConstants.Operations.REPLACE || operation === TableConstants.Operations.MERGE) {
    webResource.withHeader(HeaderConstants.IF_MATCH, entityResult.getEtag(entityDescriptor) || '*');
  }
 
  var entitySerializedDescriptor;
  if (!(operation === TableConstants.Operations.DELETE || operation === TableConstants.Operations.RETRIEVE)) {
    entitySerializedDescriptor = entityResult.serialize(entityDescriptor);
  }
 
  exports.setTableRequestHeadersAndBody(webResource, entitySerializedDescriptor, options.payloadFormat);
 
  return webResource;
};
 
/**
* Sets the table request headers.
*
* @param {string}             webResource       The webResource to add headers to.
* @param {object}             [body]            The body of the request.
*/
exports.setTableRequestHeadersAndBody = function (webResource, body, acceptType) {
  if (body) {
    webResource.withHeader(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(body, 'utf8'))
      .withBody(body)
      .withHeader(HeaderConstants.CONTENT_TYPE, HeaderConstants.JSON_CONTENT_TYPE_VALUE);
  }
 
  webResource.withHeader(HeaderConstants.ACCEPT, acceptType)
    .withHeader(HeaderConstants.MAX_DATA_SERVICE_VERSION, TableConstants.DEFAULT_DATA_SERVICE_VERSION);
};
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/internal/sharedkeytable.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/internal/sharedkeytable.js

Statements: 41.38% (12 / 29)      Branches: 0% (0 / 6)      Functions: 0% (0 / 4)      Lines: 41.38% (12 / 29)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93                                  1 1 1 1 1 1 1                   1             1               1                                                     1                               1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var util = require('util');
var azureCommon = require('./../../../common/common');
var SharedKey = azureCommon.SharedKey;
var azureutil = azureCommon.util;
var Constants = azureCommon.Constants;
var HeaderConstants = Constants.HeaderConstants;
var QueryStringConstants = Constants.QueryStringConstants;
 
/**
* Creates a new SharedKeyTable object.
*
* @constructor
* @param {string} storageAccount    The storage account.
* @param {string} storageAccessKey  The storage account's access key.
* @param {bool}   usePathStyleUri   Boolean value indicating if the path, or the hostname, should include the storage account.
*/
function SharedKeyTable(storageAccount, storageAccessKey, usePathStyleUri) {
  SharedKeyTable['super_'].call(this,
    storageAccount,
    storageAccessKey,
    usePathStyleUri);
}
 
util.inherits(SharedKeyTable, SharedKey);
 
/**
* Signs a request with the Authentication header.
*
* @param {WebResource} The webresource to be signed.
* @param {function(error)}  callback  The callback function.
*/
SharedKeyTable.prototype.signRequest = function (webResource, callback) {
  var getvalueToAppend = function (value) {
    if (azureutil.objectIsNull(value)) {
      return '\n';
    } else {
      return value + '\n';
    }
  };
 
  var stringToSign =
      webResource.method + '\n' +
      getvalueToAppend(webResource.headers[HeaderConstants.CONTENT_MD5]) +
      getvalueToAppend(webResource.headers[HeaderConstants.CONTENT_TYPE]) +
      getvalueToAppend(webResource.headers[HeaderConstants.MS_DATE]) +
      this._getCanonicalizedResource(webResource);
 
  var signature = this.signer.sign(stringToSign);
 
  webResource.withHeader(HeaderConstants.AUTHORIZATION, 'SharedKey ' + this.storageAccount + ':' + signature);
  callback(null);
};
 
/*
* Retrieves the webresource's canonicalized resource string.
* @param {WebResource} webResource The webresource to get the canonicalized resource string from.
* @return {string} The canonicalized resource string.
*/
SharedKeyTable.prototype._getCanonicalizedResource = function (webResource) {
  var path = '/';
  if (webResource.path) {
    path = webResource.path;
  }
 
  var canonicalizedResource = '/' + this.storageAccount + path;
 
  var queryStringValues = webResource.queryString;
  if (queryStringValues[QueryStringConstants.COMP]) {
    canonicalizedResource += '?comp=' + queryStringValues[QueryStringConstants.COMP];
  }
 
  return canonicalizedResource;
};
 
module.exports = SharedKeyTable;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/models/

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/models/

Statements: 23.19% (32 / 138)      Branches: 0% (0 / 60)      Functions: 0% (0 / 17)      Lines: 23.19% (32 / 138)      Ignored: none     

All files » node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/models/
File Statements Branches Functions Lines
batchresult.js 17% (17 / 100) 0% (0 / 44) 0% (0 / 10) 17% (17 / 100)
entityresult.js 37.04% (10 / 27) 0% (0 / 14) 0% (0 / 4) 37.04% (10 / 27)
tableresult.js 45.45% (5 / 11) 0% (0 / 2) 0% (0 / 3) 45.45% (5 / 11)
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/models/batchresult.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/models/batchresult.js

Statements: 17% (17 / 100)      Branches: 0% (0 / 44)      Functions: 0% (0 / 10)      Lines: 17% (17 / 100)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233                                  1 1 1 1 1 1 1   1 1                     1                           1                   1                                 1                                                             1                                                               1                                                                   1                                                                                                               1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var azureCommon = require('./../../../common/common');
var Md5Wrapper = require('./../../../common/md5-wrapper');
var StorageServiceClient = azureCommon.StorageServiceClient;
var WebResource = azureCommon.WebResource;
var Constants = azureCommon.Constants;
var HeaderConstants = Constants.HeaderConstants;
var TableConstants = Constants.TableConstants;
 
var RequestHandler = require('../internal/requesthandler');
var entityResult = require('./entityresult');
 
/**
* Creates a new BatchResult.
*
* @param {TableService}      tableService    The table service.
* @param {string}            table           The table name.
* @param {array}             operations      The array of batch operations.
* @constructor
* @ignore
*/
function BatchResult(tableService, table, operations) {
  this.tableService = tableService;
  this.table = table;
  this.operations = operations;
  this.batchBoundary = 'batch_' + BatchResult._getBoundary();
  this.changesetBoundary = 'changeset_' + BatchResult._getBoundary();
}
 
/**
* Gets a boundary string.
*
* @return {string}   The boundary string.
* @ignore
*/
BatchResult._getBoundary = function () {
  return (new Md5Wrapper().createMd5Hash()).update('' + (new Date()).getTime()).digest('hex');
};
 
/**
* Constructs the batch web request.
*
* @return {WebResource}   The batch WebResource.
* @ignore
*/
BatchResult.prototype.constructWebResource = function () {
  var webResource = WebResource.post('$batch')
    .withRawResponse(true);
 
  webResource.withHeader(HeaderConstants.CONTENT_TYPE, 'multipart/mixed; charset="utf-8"; boundary=' + this.batchBoundary);
  webResource.withHeader(HeaderConstants.DATA_SERVICE_VERSION, '3.0;');
  webResource.withHeader(HeaderConstants.MAX_DATA_SERVICE_VERSION, '3.0;NetFx');
 
  return webResource;
};
 
/**
* Serializes the batch web body.
*
* @return {string}      The serialized batch content.
* @ignore
*/
BatchResult.prototype.serialize = function () {
  var body = '--' + this.batchBoundary + '\n';
  
  if (this.operations.length === 1 && this.operations[0].type === TableConstants.Operations.RETRIEVE) {
    body += HeaderConstants.CONTENT_TYPE + ': application/http\n';
    body += HeaderConstants.CONTENT_TRANSFER_ENCODING + ': binary\n\n';
    body += this._serializeOperation(this.operations[0]);
  } else {
    body += HeaderConstants.CONTENT_TYPE + ': multipart/mixed;charset="utf-8";boundary=' + this.changesetBoundary + '\n\n';
 
    for (var i = 0; i < this.operations.length; i++) {
      body += '--' + this.changesetBoundary + '\n';
      body += HeaderConstants.CONTENT_TYPE + ': application/http\n';
      body += HeaderConstants.CONTENT_TRANSFER_ENCODING + ': binary\n\n';
      body += this._serializeOperation(this.operations[i], i) + '\n';
    }
    body += '--' + this.changesetBoundary + '--\n';
  } 
  body += '--' + this.batchBoundary + '--';
 
  return body;
};
 
/**
* Serializes a request within the batch.
*
* @param {object}       The operation to serialize.  
* @param {number}       The index of the operation in the operations arrray.
* @return {string}      The serialized operation content.
* @ignore
*/
BatchResult.prototype._serializeOperation = function (operation, count) {
  operation.options.payloadFormat = operation.options.payloadFormat || this.tableService.defaultPayloadFormat;
  var webResource = RequestHandler.constructEntityWebResource(operation.type, this.table, operation.entity, operation.options);
 
  if (count) {
    webResource.headers[HeaderConstants.CONTENT_ID] = count;
  }
 
  if (webResource.headers[HeaderConstants.CONTENT_TYPE]) {
    webResource.headers[HeaderConstants.CONTENT_TYPE] += 'type=entry';
  }
 
  this.tableService._setRequestUrl(webResource);
 
  var content = webResource.method + ' ' + webResource.uri + ' HTTP/1.1\n';
 
  Object.keys(webResource.headers).forEach(function (header) {
    content += header + ': ' + webResource.headers[header] + '\n';
  });
 
  content += '\n';
  content += webResource.body || '';
 
  return content;
};
 
/**
* Parses a batch response.
*
* @param {object} responseObject    The response object for the batch request.
* @return {array} An array with the processed / parsed responses.
*/
BatchResult.prototype.parse = function (responseObject) {
  var responses = null;
  if (responseObject && responseObject.response && responseObject.response.body &&
      typeof responseObject.response.body === 'string') {
    responses = [];
    var rawResponses = responseObject.response.body.split(TableConstants.CHANGESET_DELIMITER);
 
    if(rawResponses.length === 1) {
      rawResponses = responseObject.response.body.split(TableConstants.BATCH_DELIMITER);
    }
 
    var self = this;
    rawResponses.forEach(function (rawResponse) {
      // Find HTTP/1.1 CODE line
      var httpLocation = rawResponse.indexOf('HTTP/1.1');
      if (httpLocation !== -1) {
        rawResponse = rawResponse.substring(httpLocation);
 
        // valid response
        var response = self._parseOperation(rawResponse);
        responses.push(response);
      }
    });
  }
 
  return responses;
};
 
/**
* Parses a partial response.
*
* @param {string}      rawResponse      The raw, unparsed, http response from the server for the batch response.
* @return {object}      A response object.
*/
BatchResult.prototype._parseOperation = function (rawResponse) {
  var responseObject = {
    error: null,
    response: { }
  };
 
  // Split into multiple lines and process them
  var responseLines = rawResponse.split('\r\n');
 
  if (responseLines.length > 0) {
    // Retrieve response code
    var headers = responseLines.shift().split(' ');
    if (headers.length >= 2) {
      responseObject.response.statusCode = parseInt(headers[1]);
      responseObject.response.isSuccessful = WebResource.validResponse(responseObject.response.statusCode);
    }
 
    // Populate headers
    responseObject.response.headers = { };
    responseObject.response.body = '';
 
    var isBody = false;
    responseLines.forEach(function (line) {
      if (line === '' && !isBody) {
        isBody = true;
      } else if (isBody) {
        responseObject.response.body += line;
      } else {
        var headerSplit = line.indexOf(':');
        if (headerSplit !== -1) {
          responseObject.response.headers[line.substring(0, headerSplit).trim().toLowerCase()] = line.substring(headerSplit + 1).trim();
        }
      }
    });
 
    StorageServiceClient._parseResponse(responseObject.response, this.tableService.xml2jsSettings);
    if (!responseObject.response.isSuccessful) {
      responseObject.error = StorageServiceClient._normalizeError(responseObject.response.body, responseObject.response);
    }
 
    if (!responseObject.error) {
      var index = responseObject.response.headers[HeaderConstants.CONTENT_ID] || 0;
      var propertyResolver;
      var entityResolver;
      if (index && this.operations[index]) {
        var options = this.operations[index].options;
        propertyResolver = options.propertyResolver;
        entityResolver = options.entityResolver;
      } 
      responseObject.entity = entityResult.parseEntity(responseObject.response, propertyResolver, entityResolver);
    }
  }
 
  return responseObject;
};
 
module.exports = BatchResult;
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/models/entityresult.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/models/entityresult.js

Statements: 37.04% (10 / 27)      Branches: 0% (0 / 14)      Functions: 0% (0 / 4)      Lines: 37.04% (10 / 27)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63                                  1 1 1 1 1   1   1       1                 1                                 1              
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var azureCommon = require('./../../../common/common');
var Constants = azureCommon.Constants;
var TableConstants = Constants.TableConstants;
var HeaderConstants = Constants.HeaderConstants;
var odataHandler = require('../internal/odatahandler');
 
exports = module.exports;
 
exports.serialize = function (entity) {
  return odataHandler.serializeJson(entity);
};
 
exports.parseQuery = function (response, autoResolveProperties, propertyResolver, entityResolver) {
  var result = {};
  if (response.body) {
    result = odataHandler.parseJsonEntities(response.body, autoResolveProperties, propertyResolver, entityResolver);
  }
 
  return result;
};
 
exports.parseEntity = function (response, autoResolveProperties, propertyResolver, entityResolver) {
  var result = {};
  if (response.body) {
    result = odataHandler.parseJsonSingleEntity(response.body, autoResolveProperties, propertyResolver, entityResolver);
  }
 
  if (response.headers && response.headers[HeaderConstants.ETAG.toLowerCase()]) {
    if (!result[TableConstants.ODATA_METADATA_MARKER]) {
      result[TableConstants.ODATA_METADATA_MARKER] = {};
    }
 
    result[TableConstants.ODATA_METADATA_MARKER].etag = response.headers[HeaderConstants.ETAG.toLowerCase()];
  }
 
  return result;
};
 
exports.getEtag = function (entity) {
  var etag;
  if (entity && entity[TableConstants.ODATA_METADATA_MARKER]) {
    etag = entity[TableConstants.ODATA_METADATA_MARKER].etag;
  } 
  return etag;
};
 
Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/models/tableresult.js

npmtest-azure-storage (v0.0.1)

Code coverage report for node-npmtest-azure-storage/node_modules/azure-storage/lib/services/table/models/tableresult.js

Statements: 45.45% (5 / 11)      Branches: 0% (0 / 2)      Functions: 0% (0 / 3)      Lines: 45.45% (5 / 11)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38                                  1   1       1       1                 1  
// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 
 
// Module dependencies.
var odataHandler = require('../internal/odatahandler');
 
function TableResult(name) {
  this.name = name;
}
 
TableResult.serialize = function (tableName) {
  return JSON.stringify({ TableName: tableName });
};
 
TableResult.parse = function (response) {
  var result = null;
  if (response.body) {
    result = odataHandler.parseJsonTables(response.body);
  }
 
  return result;
};
 
exports = module.exports = TableResult;